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

Introduction

ergon is a set of Rust crates you can use on their own. ergo-sbe generates Simple Binary Encoding codecs. ergo-aeron-cluster is an experimental Aeron Cluster client. ergon-tune reads a host and names the settings that will wreck a tail latency. The Kubernetes pieces give a pod exclusive CPUs and a latency-pod policy. You do not need a cluster to generate a codec, and you do not need the other crates to use one of them.

0.x alpha: any release may break the API, with no deprecation period. Pin exact versions and read the changelog before upgrading. Exit criteria: Road to 1.0.

How to read this book

The sidebar has one part per module. A module with deep pages has two parts, start here (the light pages) and in depth. Stop after the light pages and go to the next module, or carry on into the deep pages. Each module’s samples sit in its own part, and the detail chapters are linked by name.

Module (sidebar part)Light pagesDeep pagesFor
ergo-sbeGetting started, feature tourCore concepts, configuration, recipes, design notes, benchmarks, samples (including build patterns and the buffer sizing guide)Anyone with an SBE schema who wants Rust codecs
ergo-sbe-inspectInspect bytes with no codec, the sbe-inspect filterHow a reading is chosen, framing detectionAnyone who has SBE bytes and schemas but no compiled codec
ergo-aeronergo-aeron, live messages, scripts and pipesDriver tabs, counters, attached or embedded, archive tabs, in KubernetesAnyone who runs an Aeron media driver or archive
ergo-aeron-clusterCluster client, cluster tutorialSessionBuilder, egress, chained decoding, compatibility, HA order book, RFQAnyone who needs an Aeron Cluster client (experimental)
ergon-tuneHost checksNone: one pageAnyone starting a process on a latency host
Kubernetes and deploymentShared CPUs, latency podsLow-latency hosts and its pagesAnyone deploying a busy-spin pod
ProjectContributing, Road to 1.0Verification and release, performance, AI assistanceContributors and reviewers
flowchart LR
  schema["schema XML"] --> gen["ergo-sbe in build.rs"]
  gen --> enc["try_wrap or wrap"]
  enc --> fields["fields in wire order"]
  fields --> bytes["SBE frame"]
  bytes --> dec["try_decode"]
  dec --> view["flyweight view or owned snapshot"]

A message written out of tail order is a compile error. Checked constructors return Result; the three constructor tiers are specified in one place, Trust boundary. Size the buffer with the generated length API before you write; the rule table is Buffer sizing.

Crates

CrateWhat it doesWhen to use it
ergo-sbeGenerates Rust SBE codecs from schema XML. Wire layout matches official SBE for the published profile. Generated codecs embed sbe_rt, so the generator is not on the hot path.You have an SBE schema and want encode and decode in Rust. ergo_sbe::generate(source, config)?.write_to_out_dir()? in build.rs, then include! or ergo_sbe::sbe_mod!(name) (Depend).
ergo-sbe-inspectReads SBE bytes at run time against any number of schemas: which message, how sure, and every candidate when it cannot choose. No generated code.You have bytes and schemas but no compiled codec (overview).
ergo-aeron-toolsergo-aeron: an Aeron media driver’s counters, streams, errors, loss and messages, and an archive’s recordings, in a terminal UI or a pipe.You run an Aeron driver and want to see what it is doing (overview).
ergon-tuneReads the host and names what will wreck a tail latency, and the fix.At start-up on a latency host. It changes nothing (Host checks).
ergo-aeron-clusterAn Aeron Cluster client.You need a cluster client. Experimental, not a production substitute (overview).
PieceWhat it doesWhen to use it
k8s/nri-shared-cpusGives a pod its exclusive CPUs and the node’s shared housekeeping CPUs, and starts every thread on the shared ones so the busy-spin loop keeps its core.A pod that spins on exclusive CPUs. Chart oci://ghcr.io/mimran1980/charts/ergon-shared-cpus version 0.1.6, image ghcr.io/mimran1980/ergon-shared-cpus:0.1.6. Prepare the node first (chapter).
k8s/nri-latency-podsNode tuning and the hot-pod admission policy: no exec probes, no always-restart sidecars. The grants live in the shared-cpus image.After the chart. Apply the admission YAML, then label hot pods ergon.io/latency: hot (chapter).

Start with ergo-sbe. Add another row only for a need you have.

Flyweight or an owned snapshot

You haveUseCost
A few fields, and the work finishes while the frame is borrowedThe flyweight decoder (price(), and so on)No whole-message copy
A value that must outlive the bufferThe owned *Domain snapshot from with_domain_objectsAllocates. Tooling and logs, not a hot path

The full comparison, including *FixedFields and the *Source trait, is Flyweight vs whole struct. Mapping a wire field to an application type (with_conversion or with_domain_type) is a different switch: with_conversion vs with_domain_type.

Detail chapters

Read these when the light pages are not enough. Each topic is written in full on the page named here.

TopicChapter
Constructor tiers, acting block length, and group tailsTrust boundary
compute_length_with_header and *EncodedLengthBuffer sizing
Borrowed view versus owned snapshotFlyweight vs whole struct
with_conversion versus with_domain_typewith_conversion vs with_domain_type
Wire order as named stagesWire order
Cluster session, egress, chained decode, compatibilitySessionBuilder, egress, chained decoding, compatibility
Node tuning and clocksHFT tuning, clocks

Use the animations

The diagrams in the detail chapters show work and ownership step by step. Use Next to inspect one transition, Back to compare it with the previous state, or Play for the whole sequence, or drag the timeline directly to a step. With focus inside a diagram, arrow keys step and Space plays or pauses. Reduced-motion preferences turn movement off; the controls still work. Each diagram has captions and an accompanying text explanation, so its lesson also works without animation or JavaScript. Schematic widths and illustrative byte counts are labelled; movement is not a timing measurement.

A first encode

[build-dependencies]
ergo-sbe = "0.1"

[dependencies]
ergo-sbe = "0.1"   # only for sbe_mod! / include_sbe!
#![allow(unused)]
fn main() {
let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
// Buffer is exact size from const compute_length_with_header — no bounds check needed.
let len = HeartbeatEncoder::try_wrap_and_apply_header(&mut buf, 0)?
    .fixed(&HeartbeatFixedFields { sequence: 7, timestamp: 0 })
    .encoded_length_with_header();
let dec = HeartbeatDecoder::try_from(&buf[..len])?;
assert_eq!(dec.sequence(), 7);
}

(From book/examples/heartbeat-encode.rs, compiled against the feature-tour codec.)

Set up → · Feature tour → · Coming from sbe-tool →

Nested groups use scoped closures, so you do not hand encoder ownership back with .parent():

#![allow(unused)]
fn main() {
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

(Compiled and run in CI.)

It is not a line-for-line port of sbe-tool. The generated API is meant to be easier under Rust’s borrow checker, safer at untrusted boundaries, and still official-SBE on the wire for the shapes under test. Wire parity is tested by the dual-encode suite (sbe_tool_wire_parity_test, sbe_tool_multi_schema_wire_parity_test). The benchmarks also assert byte parity before timing: Benchmarks. Encode and decode of the generated codecs do not allocate on the hot path (allocation_count_test).

Hosts and Kubernetes: Deployment. Which clock to read: Clocks.

Rust 1.99+. Clone setup and checks: repository README.

Getting started

Add ergo-sbe as a build dependency, generate a module, include it, encode and decode.

Depend on the generator

The minimal path is codegen only. Generated codecs embed their own sbe_rt and do not link ergo-sbe into the application. Schema parse errors render a source snippet (line and span) by default:

[build-dependencies]
ergo-sbe = "0.1"
# no [dependencies] ergo-sbe

For convenience, also add ergo-sbe as a normal dependency when you use sbe_mod! or include_sbe! (the macros expand in the app crate):

[build-dependencies]
ergo-sbe = "0.1"

[dependencies]
ergo-sbe = "0.1"   # only needed for sbe_mod! / include_sbe!

See Samples for monorepo crates that use each pattern.

Generate in build.rs

One call parses the schema and generates the codec: generate(source, config). Then write the result:

Write withOutputUse when
.write_to_out_dir()Cargo’s $OUT_DIR; include with ergo_sbe::sbe_mod!(name) or include!Products: nothing generated lands in the source tree
.write_to(dir)A directory you choose, e.g. a gitignored src/generated/rust-analyzer go-to-definition into the generated code

Both publish every module or none, print cargo::rerun-if-changed for the schema file and every resolved include, and print generation warnings as cargo::warning.

SourceMeans
SchemaSource::file(path) (or a &Path or PathBuf)Reads the file; xi:include resolves relative to it
SchemaSource::xml(text)Inline XML, for example from include_str!; nothing to watch, so add your own rerun-if-changed

A bare &str does not compile as a source: say whether it is a path or XML.

The feature-tour sample writes to src/generated/:

#![allow(unused)]
fn main() {
    let generated_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/generated");
    let config = ergo_sbe::GenerationConfig::new("feature_tour")
        .with_domain_objects(ergo_sbe::DomainVarData::Strings)
        .with_domain_type(
            ergo_sbe::ConversionSelector::named_type("BooleanType"),
            "bool",
        )
        .with_domain_type(
            ergo_sbe::ConversionSelector::semantic_type("UTCTimestamp"),
            "chrono::DateTime<chrono::Utc>",
        )
        .with_conversion(ergo_sbe::ConversionSelector::named_type("Decimal"))
        // Same shape as Decimal, but the app supplies the impl itself; see
        // demo_domain_type_manual_impl in src/lib.rs.
        .with_manual_domain_type(
            ergo_sbe::ConversionSelector::named_type("ManualDecimal"),
            "rust_decimal::Decimal",
        );

    ergo_sbe::generate(
        ergo_sbe::SchemaSource::file("schemas/feature-tour.xml"),
        config,
    )?
    .write_to(&generated_dir)?;
}

generate is parse + Schema::from_ir + Generator::generate. Call those directly to inspect the token IR or to generate several schemas that share types: see Multi-Schema Patterns.

Include generated code

Product crates should depend on ergo-sbe at build time only, with no runtime link. Generated codecs embed sbe_rt, so plain include! is enough:

#[path = "generated/feature_tour.rs"]
pub mod feature_tour;
pub use feature_tour::*;

(From sbe-feature-tour/src/lib.rs: the #[path] pattern used by every sample crate. The feature tour’s cargo build checks that it compiles.)

or via include!:

mod messages {
    include!(concat!(env!("OUT_DIR"), "/messages.rs"));
}
use messages::*;

sbe_mod! is optional and needs ergo-sbe as a normal dependency (for macro expansion only, not for encode or decode):

// Cargo.toml: [dependencies] ergo-sbe = "0.1"
ergo_sbe::sbe_mod!(messages);
use messages::*;
// Or only the include: ergo_sbe::include_sbe!("messages");

See Samples for which crates use which pattern.

Encode and decode

There are two styles:

fixed() takes a struct that fills every field at once; a missing field is a compile error:

#![allow(unused)]
fn main() {
pub fn demo_fixed_heartbeat() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    // Const length → stack array (no heap).
    let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
    let nanos: i64 = 1_720_000_000_000_000_000;
    // Buffer pre-sized via const compute_length_with_header; try_* still validates extent.
    let written = HeartbeatEncoder::try_wrap_and_apply_header(&mut buf, 0)
        .unwrap()
        .fixed(&HeartbeatFixedFields {
            sequence: 7,
            timestamp: nanos as u64,
        })
        .encoded_length_with_header();

    let dec = HeartbeatDecoder::try_decode(&buf[..written], 0)?;
    assert_eq!(dec.sequence(), 7);
    let decoded_ts: DateTime<Utc> = dec.timestamp()?;
    assert_eq!(decoded_ts.timestamp_nanos_opt(), Some(nanos));
    Ok(buf[..written].to_vec())
}
}

(This code comes from the sbe-feature-tour sample crate.)

{Msg}FixedFields has no Default. Every required scalar must appear in the struct literal (optional fields use Option only when schema presence="optional"). That is intentional: zero-filling required IDs hides bugs. For large messages, build the literal next to the encode call in wire order.

On a fixed-only message (no groups or var-data), as_bytes_with_header, as_body_bytes, encoded_length*, and into_remaining_mut exist only after fixed(&FixedFields). Calling them on the value returned by wrap* is a type error, which stops a reused buffer from publishing leftover body bytes or packing the next message over a stale body.

Individual setters stay on the unfixed encoder after wrap* and also on raw_fixed() (body-relative offsets). Prefer fixed(&FixedFields) when you have every field; use raw_fixed() when you want a dedicated writer:

#![allow(unused)]
fn main() {
// Dedicated raw writer (setters also exist on the unfixed encoder).
// `as_bytes_with_header` is only on FieldsFixed after `fixed(&FixedFields)`.
let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
let mut w = HeartbeatEncoder::try_wrap_and_apply_header(&mut buf, 0)?
    .raw_fixed();
w.sequence(7);
w.timestamp_wire(0);
let dec = HeartbeatDecoder::try_from(&buf[..HeartbeatEncoder::ENCODED_LENGTH])?;
assert_eq!(dec.sequence(), 7);
}

(From book/examples/heartbeat-encode.rs, compiled against the feature-tour codec.)

raw_fixed() writes into the buffer you already sized. It does not mark the message complete: omitted required setters leave stale bytes, and as_bytes_with_header / encoded_length* / into_remaining_mut stay locked. Set every required field, then call fixed(&FixedFields) for the complete-message views. Slicing &buf[..ENCODED_LENGTH] yourself is possible but is not the completeness-checked path.

Optional fields and apply_nulls

try_wrap_and_apply_header / wrap_and_apply_header write the message header only. They do not fill optional fixed fields with schema null sentinels (sbe-tool parity). Unwritten optional bytes retain whatever was already in the buffer (often zero, sometimes stale).

fixed() closes that gap. Optional fields are Option<T> in the generated FixedFields struct, and fixed() writes the schema null wire image for every None, including fixed arrays and nested optional composite members. Since fixed() is the only route to a message’s tails and to fixed-only complete byte views, the ordinary path never leaves a stale optional behind:

// `price` is optional; None writes the schema null image, not stale bytes.
// (Illustrative: use your schema's message name and optional field.)
let len = OrderEncoder::wrap_and_apply_header(&mut buf, 0)
    .fixed(&OrderFixedFields { symbol: *b"IBM     ", price: None })
    .encoded_length_with_header();

apply_nulls() remains on the unfixed encoder after wrap*, for the case where you set individual optional fields yourself and no FixedFields value describes which optionals are unset. It is generated only for messages that declare at least one optional field, and it is the counterpart to sbe-tool’s nullify_optional_fields().

Group entries need no call at all. Every add(), add_checked() and start_entry() writes the null image for the entry’s optional fields before your setters run, so a reused buffer cannot leak a previous entry’s value. It is the image fixed() writes for a None, for every shape: scalars and enums take their null value, a fixed array takes the element null in every slot, and an optional composite is zeroed and its optional members nulled.

See Why NullVal Instead of Option and, when porting, Coming from sbe-tool.

Fixed-width char fields become [u8; N]. Pass a shorter &str via the _str setter, which pads with NULs. On decode, copy_* copies the raw bytes into your buffer, or read the slice with vehicle_code():

#![allow(unused)]
fn main() {
let complete_len = CarEncoder::compute_length()
    .fuel_figures_ragged(0, |_| Ok(()))?
    .performance_figures_ragged(0, |_| Ok(()))?
    .manufacturer(5)?
    .model(5)?
    .activation_code(3)?
    .encoded_length_with_header();
const PAD: usize = 256;
assert!(complete_len <= PAD, "car length {complete_len} exceeds pad {PAD}");
let mut storage = [0u8; PAD];
let buf = &mut storage[..complete_len];
let fields = CarFixedFields {
    serial_number: 1234,
    model_year: 2013,
    available: true.into(),
    code: Model::A,
    some_numbers: [10, 20, 30, 40],
    vehicle_code: *b"ABCDEF",
    extras: OptionalExtras::default(),
    engine: Engine::new(2000, 4, *b"123", 0i8, false.into(), Booster::new(BoostType::TURBO, 210)),
};
let n = CarEncoder::try_wrap_and_apply_header(buf, 0)?
    .fixed(&fields)
    .fuel_figures(0, |_| Ok(()))?
    .performance_figures(0, |_| Ok(()))?
    .manufacturer_as_str("Honda")?
    .model_as_str("Civic")?
    .activation_code_as_str("abc")?
    .encoded_length_with_header();
assert_eq!(n, complete_len);

let car = CarDecoder::try_from(&buf[..n])?;
let mut dst = [0u8; 6];
assert_eq!(car.copy_vehicle_code(&mut dst), 6);
assert_eq!(&dst, b"ABCDEF");
assert_eq!(car.vehicle_code(), *b"ABCDEF");
}

(From book/examples/fixed-char-arrays.rs, compiled against the feature-tour codec.)

The Car encoder’s fixed fields include vehicle_code: [u8; 6] (schema char array) and some_numbers: [u32; 4]. See the feature tour for the complete Car example with groups and var-data.

For a runnable map of the features, start with sbe-feature-tour (cargo run --manifest-path samples/sbe-feature-tour/Cargo.toml).
More recipes: Recipes.

Method Chaining

ergo-sbe encoders are designed so the entire encode reads as one expression, from wrap_and_apply_header through .fixed(...) and every dynamic tail, ending in .encoded_length_with_header(). Bind only the resulting length; do not retain intermediate encoder variables.

Prefer (one chain, one let):

#![allow(unused)]
fn main() {
let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
// Buffer is exact size from const compute_length_with_header — no bounds check needed.
let len = HeartbeatEncoder::try_wrap_and_apply_header(&mut buf, 0)?
    .fixed(&HeartbeatFixedFields { sequence: 7, timestamp: 0 })
    .encoded_length_with_header();
let dec = HeartbeatDecoder::try_from(&buf[..len])?;
assert_eq!(dec.sequence(), 7);
}

(From book/examples/heartbeat-encode.rs, compiled against the feature-tour codec.)

Staged chaining vs fixed-only

For a fixed-only message like Heartbeat, wrap* returns HeartbeatEncoder<'_, H, FieldsUnfixed>. .fixed(&HeartbeatFixedFields { … }) consumes that value and returns FieldsFixed, which is the only phase that exposes as_bytes_with_header / as_body_bytes / encoded_length* / into_remaining_mut. Individual field setters stay on the unfixed phase and on raw_fixed(); they are not on that complete view.

Avoid (interrupted chain, rebinding):

// Each `let` breaks the chain and splays the pipeline across the screen.
// The `.unwrap()` calls are a code smell; the fallible chain should use `?`.
let enc = CarEncoder::wrap_and_apply_header(&mut buf, 0).fixed(&fields);
let enc = enc.fuel_figures(2, |g| { ... }).unwrap();
let enc = enc.performance_figures(0, |_| Ok(())).unwrap();
let enc = enc.manufacturer_as_str("Honda").unwrap();
let enc = enc.model_as_str("Civic VTi").unwrap();
let enc = enc.activation_code_as_str("abcdef").unwrap();
let len = enc.encoded_length_with_header();

Every encoder stage is chainable: fixed() and each tail method return the next stage (or Result<NextStage, _>) and compose with ? in the same expression. Intermediate encoder rebinding and manual .unwrap() defeat this design.

For the full Car example with groups and var-data, see the feature tour page.

Decoding

Sequential decode consumes each tail in wire order. For callbacks throughout the chain, start with decoder.ordered():

#![allow(unused)]
fn main() {
pub fn demo_car_ordered_lane(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let mut speeds = Vec::new();
    let mut octanes = Vec::new();
    let mut text = Vec::new();

    let len = CarDecoder::try_decode(wire, 0)?
        .ordered()
        .fixed(|car| {
            assert_eq!(car.serial_number(), 1234);
            Ok(())
        })?
        .fuel_figures(|entry, info| {
            // `info` carries the position the wire declares.
            assert_eq!(info.count, 2);
            assert_eq!(info.is_last(), info.index == 1);
            speeds.push(entry.speed());
            Ok(entry.ordered().usage_description(|_| Ok(()))?)
        })?
        .performance_figures(|entry, _info| {
            octanes.push(entry.octane_rating());
            Ok(entry.ordered().acceleration(|a, _| {
                let _ = (a.mph(), a.seconds());
                Ok(())
            })?)
        })?
        .manufacturer_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .model_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .activation_code_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .encoded_length_with_header();

    assert_eq!(speeds, vec![30, 60]);
    assert_eq!(octanes, vec![95]);
    assert_eq!(text, vec!["Honda", "Civic VTi", "abcdef"]);
    assert_eq!(len, wire.len());
    Ok(())
}
}

The fixed callback comes before tails and receives a fixed-fields-only view; each group callback receives the entry and its EntryInfo, and var-data callbacks receive bytes or strictly validated text. Every callback returns Result<_, DecodeError>, so the closures infer. These callbacks borrow the original wire buffer, so bytes and text may be retained as the chain advances. The message chain ends on encoded_length_with_header() / as_bytes_with_header(), like encode; .done() is only to unwrap the staged complete. A nested ordered() walk returns that completion to the parent callback directly. The L3 sample shows this recursive form.

The underlying staged API also supports explicit iteration and skipping. Its group and var-data spellings can require iterator and tuple bindings:

Group entriesinto_<group> gives youWhy
Carry their own groups or var-dataa visit closure, returning the entry’s completionno stride: the completion is where the next entry starts
Fixed-stride (no tails of their own)an iterator, for e in &mut iterthe next entry is offset + block length, so nothing has to be measured

Var-data into_<name>() returns (payload, next). Text fields also offer into_<name>_as_str(), with strict validation and the same tuple shape. These borrowed payloads can be retained while advancing later stages.

Prefer:

#![allow(unused)]
fn main() {
pub fn demo_car_decode_stages(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let car = CarDecoder::try_decode(wire, 0)?;
    assert_eq!(car.serial_number(), 1234);
    assert_eq!(car.model_year(), 2013);
    // Domain conversion: BooleanType → bool when configured.
    let available: bool = car.available()?;
    assert!(available);
    assert_eq!(car.code(), Model::A);
    assert_eq!(car.discounted_model(), Model::C); // constant field
    assert_eq!(car.engine().capacity(), 2000);

    // Schema order: groups then var-data, one chain. Both of Car's groups have
    // entries that carry their own tails, so both take a visit closure: the
    // completion the closure returns is where the next entry starts, so the
    // group is walked exactly once.
    let mut speeds = Vec::new();
    let mut octanes = Vec::new();
    let (mfr, decoder) = car
        .into_fuel_figures(|entry| -> Result<_, sbe_rt::DecodeError> {
            speeds.push(entry.speed());
            // usageDescription is this entry's only tail, so reading it
            // completes the entry.
            entry.into_usage_description().map(|(_usage, done)| done)
        })?
        .into_performance_figures(|entry| -> Result<_, sbe_rt::DecodeError> {
            octanes.push(entry.octane_rating());
            // acceleration has fixed-stride entries, so it is a real iterator.
            let mut accel = entry.into_acceleration()?;
            assert_eq!((&mut accel).len(), 2);
            accel.finish()
        })?
        .into_manufacturer_as_str()?;
    assert_eq!(speeds, vec![30, 60]);
    assert_eq!(octanes, vec![95]);
    let (model, decoder) = decoder.into_model_as_str()?;
    let (code, _decoder) = decoder.into_activation_code_as_str()?;
    // All three &str coexist: each borrows 'a from the original wire buffer.
    assert_eq!((mfr, model, code), ("Honda", "Civic VTi", "abcdef"));
    Ok(())
}
}

(Real code from the sbe-feature-tour sample. fuelFigures and performanceFigures entries carry tails, so they take closures; acceleration is fixed-stride, so it is an iterator.)

Consecutive var-data fields chain through the next stage each tuple returns; the borrowed slices stay valid while later stages advance:

#![allow(unused)]
fn main() {
fn count_car_text_bytes(wire: &[u8]) -> Result<usize, sbe_rt::DecodeError> {
    let (manufacturer, next) = CarDecoder::try_from(wire)?
        .skip_fuel_figures()?
        .skip_performance_figures()?
        .into_manufacturer()?;
    let (model, next) = next.into_model()?;
    let (activation_code, _complete) = next.into_activation_code()?;
    Ok(manufacturer.len() + model.len() + activation_code.len())
}
}

For callbacks instead of tuples, use the ordered lane’s <name>(|bytes| ..) and <name>_as_str(|text| ..), which return DecodeError.

The generated staged walk advances once through dynamic tails. Random-access getters used before that walk, including counts or lengths for later tails, can add scans. See Asking before walking.

Multi-schema patterns

SBE schemas often share types (messageHeader, groupSizeEncoding, composites, enums, sets). ergo-sbe supports two approaches:

ApproachWhenMethod
xi:include (standard)Schema files live together; official SBE portability matters<include href="common-types.xml"/>; parse(SchemaSource::file(..)) resolves includes relative to the file
Shared Ir (programmatic)Schemas are parsed from strings, generated, or live in separate reposSchemaSource::file(..).with_shared(&common) seeds one parse from another’s resolved types

The <include> path is what the SBE spec expects. The shared-Ir path is a convenience for tooling, build scripts, and any workflow where you already have the shared schema parsed in memory.

A consumer parsed with_shared also carries the shared schema’s composites, enums and sets (not its messages) and its source files, so it generates on its own with ergo_sbe::generate, or as a consumer of a shared module below.

Shared Ir in build.rs

// build.rs
use ergo_sbe::{GenerationConfig, Generator, Schema, SchemaSource, parse};

fn main() -> ergo_sbe::miette::Result<()> {
    // 1. Parse the shared schema once (composites, enums, sets).
    let common = parse(SchemaSource::file("schemas/common-types.xml"))?;
    // 2. Parse each consumer against it; no <include> needed.
    let orders = parse(SchemaSource::file("schemas/orders.xml").with_shared(&common))?;
    let fills = parse(SchemaSource::file("schemas/fills.xml").with_shared(&common))?;
    // 3. One module per schema; the first owns the shared types.
    let (common, orders, fills) =
        (Schema::from_ir(common), Schema::from_ir(orders), Schema::from_ir(fills));
    Generator::new(GenerationConfig::new("common_types").with_shared_module("common_types"))
        .generate_multi(&[(&common, "common_types"), (&orders, "orders"), (&fills, "fills")])?
        .write_to_out_dir()?;
    Ok(())
}

With with_shared_module("common_types"), the first entry owns the shared enums/sets/composites; later entries pub use super::common_types::* and skip duplicate type generation. The name must match the first entry’s module, or generation fails with GenerateError::InvalidConfiguration.

Module names are supplied, not derived from file stems, so a hyphenated common-types.xml can emit common_types.rs. They must be unique, non-empty Rust identifiers (no path separators or keywords). Before any file is written, shared types with the same name are compared by a canonical wire fingerprint (token order, primitive encodings, offsets, presence, null/min/max, discriminants/choices, sinceVersion, and schema byte order). A name collision with a different fingerprint fails generation with GenerateError::IncompatibleSharedType rather than silently reusing the first schema’s layout. A parse or generate failure writes nothing; write_to_out_dir publishes every module or none, and watches every root and resolved include.

with_shared from in-memory strings

use ergo_sbe::{SchemaSource, parse};

let common = parse(SchemaSource::xml(
    r#"<?xml version="1.0"?>
<messageSchema package="common" id="0" version="1" byteOrder="littleEndian">
  <types>
    <composite name="messageHeader">
      <type name="blockLength" primitiveType="uint16"/>
      <type name="templateId" primitiveType="uint16"/>
      <type name="schemaId" primitiveType="uint16"/>
      <type name="version" primitiveType="uint16"/>
    </composite>
    <composite name="Price">
      <type name="mantissa" primitiveType="int64"/>
      <type name="exponent" primitiveType="int8"/>
    </composite>
  </types>
</messageSchema>"#,
))?;

// No <types> / <include>: Price resolves from `common`.
let orders = parse(
    SchemaSource::xml(
        r#"<?xml version="1.0"?>
<messageSchema package="orders" id="1" version="1" byteOrder="littleEndian"
               headerType="messageHeader">
  <message name="NewOrder" id="1">
    <field name="price" id="1" type="Price"/>
  </message>
</messageSchema>"#,
    )
    .with_shared(&common),
)?;

The shared Ir path does not recover bare top-level <type> typedefs (those are inlined during parsing and dropped from the token stream). Reference them through a <composite> / <enum> / <set> in the shared schema instead.

Consumer modules import the shared module for cross-schema type resolution:

mod common_types { include!(concat!(env!("OUT_DIR"), "/common_types.rs")); }
mod orders {
    use super::common_types::*;       // shared types + header composite
    include!(concat!(env!("OUT_DIR"), "/orders.rs"));
}
mod fills {
    use super::common_types::*;
    include!(concat!(env!("OUT_DIR"), "/fills.rs"));
}

AnyMessage is generated once per schema module. Template ids are not unique across schemas. Generate an opt-in AnySchemaMessage over every configured schema with Generator::generate_schema_dispatch:

#![allow(unused)]
fn main() {
use ergo_sbe::{GenerateError, GeneratedModule, GenerationConfig, Generator, Schema};

fn dispatcher(market: &Schema, trading: &Schema) -> Result<GeneratedModule, GenerateError> {
    Generator::new(GenerationConfig::new("market")).generate_schema_dispatch(
        &[(market, "market"), (trading, "trading")],
        "any_schema",
    )
}
}

Write the returned source to its path beside the codec modules, then include any_schema.rs in a sibling module. This also works when the codecs were generated separately with different conversion settings. Each codec must have AnyMessage dispatch enabled. The combined enum wraps it in a variant named from the module, such as Market and Trading, and reads schemaId before templateId. Decode errors retain the originating schema’s error type.

Schema ids and module names must be unique. Headers must declare the same wire layout and byte order, with a required, encoded schemaId. Custom layouts and big-endian headers work; mixed layouts or byte orders are rejected as ambiguous. Single-schema generation and the ordinary codec hot paths are unchanged.

Pass a slice bounded to one transport frame to AnySchemaMessage::decode. An unknown schema id returns Other { schema_id, template_id, frame }. An unknown template in a known schema remains that module’s AnyMessage::Unknown. Both retain the supplied header and body. as_bytes() borrows the complete frame without allocating, including future-version fields and unknown frames, for persistence or forwarding.

See also: sbe-codegen-examples (reusable generator setup), multi_schema_versioning_test (versioned schemas with shared types), exchange-example (multi-schema exchange feed with IPC).

Coming from sbe-tool

Side-by-side mapping for teams migrating from the official Simple Binary Encoding Rust generator (sbe-tool). Within the published SBE profile and docs/SBE_COMPATIBILITY.md, ergo-sbe aims for official-SBE wire fidelity with sbe-tool; the API shape is intentionally different. Do not read this as unqualified “binary compatible with every SBE feature.”

The #1 trap: wrap offset

sbe-tool Rustergo-sbe
wrap argumentBody offset (often 8 for a frame at 0)Message start (often 0)
Where fields livebody_offset + field_offsetmessage_offset + HEADER_LENGTH + field_offset
// Frame at buf[0..]:
// sbe-tool:  enc.wrap(buf, 8)              // body starts at 8
// ergo-sbe:  Enc::wrap(buf, 0)             // message starts at 0
//            Enc::wrap_and_apply_header(buf, 0)

Passing sbe-tool’s 8 into ergo-sbe for a frame at zero mis-aligns every field. Generated rustdoc on wrap / wrap_and_apply_header / decode repeats this callout.

Animation, in words: one TestMessage1 frame from the wire-parity test (tag1 7, three entries), 111 bytes that both generators write identically: header 0–8, fixed block 8–24 with tag1 at 8, group header 24–27, entries at 27, 55 and 83. Part 1, the wrap offset. sbe-tool’s wrap(buf, 8, ..) takes the body offset and reads tag1 at 8 + 0; ergo-sbe’s wrap(buf, 0, ..) takes the message start and reads at 0 + HEADER_LENGTH + 0. Both land on byte 8. Passing 8 to ergo-sbe reads tag1 from padding at byte 16 and the group header at byte 32, inside the first entry, and the extent check still passes. Passing 0 to sbe-tool’s bare wrap reads the header as tag1 (65552); sbe-tool’s header(h, 0) path takes the message start like ergo-sbe. Part 2, the cursor. sbe-tool’s decoder carries a limit: entries_decoder() consumes the decoder and moves limit 24 → 27, each advance() moves it one entry (55, 83, 111), each read checks the slice, and parent() hands back a decoder whose cursor is past the group. ergo-sbe’s base decoder has no cursor: entries() takes &self, starts at 8 + 16 = 24 every time and is Sync; the iterator owns its offset, with the group’s extent checked once. Staged into_entries() … finish() is the same single pass with the order checked at compile time. memoized() has nothing to cache on a one-group message; Decoder lanes animates a message where it pays. Counts come from the generated source, not timings; this book records no benchmark result.

Header modes (fair comparison table)

Use the same logical work on both sides when comparing or porting:

Modeergo-sbesbe-tool
Body onlywrap(buf, 0) + setters, no apply-headerwrap(buf, 8) + setters, no .header(0)
Header + bodywrap_and_apply_header(buf, 0) + setterswrap(buf, 8) then header(0).parent(), then setters
Header onlywrap_and_apply_header alonewrap(buf, 8).header(0) alone
  • ergon wrap = message start; sbe-tool wrap = body offset.
  • sbe-tool encoded_length() is body only. ergon encoded_length_with_header() includes the header. Never invent 8 + encoded_length() to “prove” a header was written if .header(0) was not called on the sbe-tool arm.

Full fairness rules for benchmarks: Benchmarks methodology.

Groups: .parent() hopscotch vs closures

sbe-toolergo-sbe
Open group flyweight, fill entries, .parent() backenc.bids(n, |bids| { bids.add(|e| { … })?; Ok(()) })?
Nested groups fight the borrow checkerNested closures end; chain continues in wire order
#![allow(unused)]
fn main() {
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

Compile-time order: you cannot call asks before bids, because the stage type has no asks method. See Wire order via named stages.

Length APIs

Conceptsbe-toolergo-sbe
Body length after encodeencoded_length()body region only via stage encoded_length where exposed
Header + bodycompute yourself (8 + …)encoded_length_with_header() / as_bytes_with_header()
Pre-size bufferoften oversize scratchExact: const Encoder::compute_length_with_header() (stack [0u8; N]), or Encoder::compute_length() / staged *EncodedLength when the length depends on groups or var-data

Do not default to vec![0u8; 4096] or Vec::with_capacity(MAX) then truncate. See Buffer sizing and Exact sizing.

Optional fields: nullify_optional_fields() and apply_nulls()

Neither generator nullifies on wrap, so in sbe-tool an optional field you never set keeps whatever was already in the buffer unless you remember to call nullify_optional_fields(). The ergon equivalent is apply_nulls(), but the port is usually to delete the call rather than rename it:

sbe-toolergo-sbe
enc.nullify_optional_fields() on the message, then set fields.fixed(&MsgFixedFields { price: None, … }); None writes the schema null image
nullify_optional_fields() on a group entry encodernothing to call: every new entry starts as the schema null image for its optional fields
Forgetting the call leaks stale bytesfixed() is the only route to tails and to complete byte views, so the ordinary path cannot leak

Optional fields are Option<T> in the generated *FixedFields struct, and fixed() writes the schema null wire image for every None, including fixed arrays and nested optional composite members.

apply_nulls() is still generated (message encoders with at least one optional field, on the unfixed stage after wrap*) for the case where you write individual optionals through raw_fixed() and have no FixedFields value describing which ones are unset.

Group entries get the same null image without a call. add(), add_checked() and start_entry() write it for every optional field before your setters run, at any nesting depth, with the bytes fixed() writes for a None. Two differences from sbe-tool’s nullify_optional_fields() to carry across:

  • An optional fixed array gets the element null in every slot. sbe-tool’s nullify leaves optional arrays untouched.
  • Only optional fields are nulled. sbe-tool also nulls the optional members of a required composite; ergon leaves a required composite to your setter.

See Optional fields and apply_nulls and Why NullVal instead of Option.

Decode entry

ergo-sbe decoder wrap and try_wrap take the message start, including the header, while sbe-tool’s wrap takes the body offset. Use try_decode when the header metadata is not already available:

Needergo-sbe
Untrusted / networktry_decode / try_wrap / try_from return Result (all failures)
Known-good bufferbare wrap panics if short; bare decode is a hybrid (panics if short, Err on wrong template/schema)
Proven-tight hot pathunsafe wrap_unchecked; decode_unchecked = unchecked extent + checked identity

See Trust Boundary.

Decoding: lanes, not one cursor

sbe-tool gives you a single &mut decoder carrying a limit cursor. Every group and var-data accessor reads at limit and advances it, so the order you call methods in is the wire walk. ergon splits that:

  • Sequential: into_* / skip_* (or decoder.ordered() for one callback per tail)
  • Random-access: try_decode, any order, Sync

A group whose entries carry their own tails takes a visit closure; a fixed-stride group hands back an iterator.

Start here when porting:

Your sbe-tool codePort to
Straight-line walk: group, group, var-data, donestaged into_* / skip_* (one traversal, compile-time tail order)
Re-wrapping the message a second time to read a field you passedthe base decoder, or decoder.memoized() if you re-read deep tails
Reading two fixed fields and dropping the restthe base decoder from try_decode: no cursor, Sync, nothing to consume
// sbe-tool: one cursor, order is a convention
let car = CarDecoder::default()
    .wrap(ReadBuf::new(buf), 8, block_len, version);   // body offset, not 0
let mut ff = car.fuel_figures_decoder();               // consumes `car`
while ff.advance()?.is_some() { /* … */ }
let mut car = ff.parent()?;                            // hand it back
let coords = car.manufacturer_decoder();               // (offset, len)
let manufacturer = car.manufacturer_slice(coords);

// ergo-sbe: consuming stages carry the next tail offset.
// fuelFigures entries carry var-data, so the step is a visit closure and the
// completion it returns is where the next entry starts: one pass, no rescan.
let (manufacturer, car) = CarDecoder::try_decode(buf, 0)?
    .into_fuel_figures(|e| e.into_usage_description().map(|(_usage, done)| done))?
    .skip_performance_figures()?
    .into_manufacturer()?;

Note what disappears in the port: no .parent() hop, no (offset, length) coordinate pair threaded to a second _slice() call, and no &mut on a decoder you only wanted to read.

Fixed-block messages (no groups, no var-data) get no memoized() or ordered(), and AnyMessage offers only into_<name>() for them. Every field is already random-access off the block.

Full per-lane pros, cons, and cost table: Decoder lanes.

Version handling

Decoders are version-aware: tail offsets use the wire acting block length, not only the compiled block length. Optional / sinceVersion fields follow schema presence rules. Prefer explicit try_* entry points when reading mixed-version streams.

What has no direct ergon equivalent (and why)

sbe-tool habitergo-sbe
.parent() ownership hopEncode: nested closures. Decode: consuming stages (a visit closure for dynamic groups, an iterator for fixed-stride ones)
One &mut decoder with a limit cursorLanes: random-access &Decoder, staged into_*, optional ordered() / .memoized() (decoder lanes)
_decoder() returning (offset, len) for a second _slice() callVar-data accessors return &'a [u8] / &'a str directly
Generic Encoder<State> spellingNamed stage structs + H: HeaderState only for header mode (type-state note)
encoded_length() as full-frame sizeUse *_with_header when you need the frame
nullify_optional_fields() on group and composite encodersEvery new group entry is written with its optional fields’ null image; only the message encoder gets apply_nulls() (above)
Always-on meta / Display noiseOpt-out size knobs: with_display_debug(false), with_meta_attributes(false), with_dispatch(false)

Trust boundary

try_* returns Result on short buffers (and identity mismatches). Bare wrap panics if short. Bare decode is a hybrid: panics if short, but still returns Err on wrong template/schema. decode_unchecked is unchecked extent + checked identity. After a safe constructor succeeds, fixed-field accessors are branch-free. Full detail: Trust Boundary.

Further reading

Error diagnostics

Schema errors use miette for pinpointed diagnostics. The generator shows what went wrong, where in the XML, and a unique error code you can match on programmatically.

Invalid type reference

Referencing a type that doesn’t exist:

<field name="badField" id="10" type="NonExistentType"/>
ergo_sbe::schema_parse::invalid

  × invalid type for field 'badField': NonExistentType
    ╭─[schema.xml:15:9]
 14 │         <!-- NonExistentType not defined -->
 15 │         <field name="badField" id="10" type="NonExistentType"/>
    ·         ───────────────────────────┬───────────────────────────
    ·                                    ╰── invalid here
 16 │     </message>
    ╰────

The error code ergo_sbe::schema_parse::invalid identifies the variant. The span points to the exact attribute. The source line and surrounding context are rendered automatically.

Missing required attribute

Omitting name on a <field>:

ergo_sbe::schema_parse::missing

  × missing field @name
    ╭─[schema.xml:15:9]
 14 │     <message name="TestMessage" id="1">
 15 │         <field id="10" type="uint8"/>
    ·         ──────────────┬──────────────
    ·                       ╰── missing here
 16 │     </message>
    ╰────

Duplicate template ID

Two messages sharing the same id:

ergo_sbe::schema_parse::resolve

  × resolution error: duplicate template id 1 for message
  │ AnotherMessageWithId1
  ╰─▶ duplicate template id 1 for message AnotherMessageWithId1

Invalid enum encoding type

ergo_sbe::schema_parse::invalid

  × invalid enum encodingType: NonExistentEncodingType
    ╭─[schema.xml:13:9]
 12 │             <!-- encodingType references non-existent type -->
 13 │ ╭─▶         <enum name="BadEnum" encodingType="NonExistentEncodingType">
 14 │ │               <validValue name="Value1">1</validValue>
 15 │ ├─▶         </enum>
    · ╰──── invalid here
 16 │         </types>
    ╰────

Multi-line spans show the full element, with the label pointing to the offending attribute.

Use in build scripts

ParseError implements miette::Diagnostic. Wrap it in miette::Report to render the full diagnostic with source context:

use ergo_sbe::{SchemaSource, parse};

match parse(SchemaSource::file("my-schema.xml")) {
    Ok(_) => { /* regenerate codec */ }
    Err(e) => {
        let report = miette::Report::new(e);
        eprintln!("{report:?}");
        std::process::exit(1);
    }
}

For programmatic handling, match on the variant directly; ParseError is a plain enum, no downcast needed. Keep a wildcard so new variants are not a compile break:

#![allow(unused)]
fn main() {
use ergo_sbe::{ParseError, SchemaSource, parse};

match parse(SchemaSource::file("my-schema.xml")) {
    Ok(_) => {}
    Err(ParseError::MalformedXml { message, .. }) => {
        eprintln!("malformed XML: {message}");
    }
    Err(ParseError::Missing { what, .. }) => {
        eprintln!("missing {what}");
    }
    Err(ParseError::Invalid { what, value, .. }) => {
        eprintln!("invalid {what}: {value}");
    }
    Err(ParseError::Resolve { error, .. }) => {
        eprintln!("resolve: {error}");
    }
    Err(ParseError::Io { path, source, .. }) => {
        eprintln!("cannot read {}: {source}", path.display());
    }
    Err(ParseError::Include { href, cause, .. }) => {
        eprintln!("include {href}: {cause}");
    }
    // Forward-compatible: ParseError is #[non_exhaustive].
    Err(other) => {
        eprintln!("{other}");
    }
}
}

Out-of-range null / min / max

A present nullValue, minValue, or maxValue is parsed fail-closed against the declared primitive width. nullValue="256" on uint8 is rejected (it is not a valid one-byte sentinel). Signed types accept the type’s full range (int8 -1 is fine; int8 128 is not).

ergo_sbe::schema_parse::invalid

  × invalid nullValue: '256' is out of range for UInt8

Without that check the generator used to emit 256_u64 as u8, so Some(0) and None collided on the wire.

Error variants

ParseError is #[non_exhaustive]. Match with a wildcard. Current variants:

VariantError codeWhen
MalformedXmlergo_sbe::schema_parse::malformed_xmlXML is not well-formed
Missingergo_sbe::schema_parse::missingRequired attribute or element absent
Invalidergo_sbe::schema_parse::invalidValue is syntactically or semantically wrong
Resolveergo_sbe::schema_parse::resolveCross-reference or schema-level validation failure
Ioergo_sbe::schema_parse::ioRoot schema file could not be read (Error::source is the std::io::Error)
Includeergo_sbe::schema_parse::includeInclude failed. cause is IncludeCause: Cycle { chain } (visit order, ending at the repeated file; a diamond/shared include is not a cycle), Io { path, source }, or NotFound. attempted lists tried paths.

Every diagnostic variant except Io carries source_code and an optional span. Include highlights the <include> element when the include was parsed from a document.

Migration from 0.1.x: IncludeError { message } is now Include { href, attempted, cause, .. }. Root read_to_string failures are Io, not MalformedXml.

Feature tour

Runnable examples pull live source from sbe-feature-tour (compiled by docs_validation_test). Schematics that cannot run in the harness stay rust,ignore.

AreaFeatureWhere
Generategenerate(..) in build.rs, write_to_out_dir / write_toGenerate in build.rs
Generatesbe_mod! / include_sbe!Include generated code
Generatebuild vs runtime dependency, generator as a libraryDepend on the generator
Generateseveral schemas, SchemaSource::with_shared, with_shared_moduleMulti-schema patterns
Generateparse diagnostics (miette spans, fancy feature)Error diagnostics
Generatevalidate_against_sbe_xsd, SchemaSource::with_xsd_validationExtension XML: what is captured
Generatemoving from sbe-toolComing from sbe-tool
Encodetype-state stages in wire orderWire order via named stages
Encodemethod chaining, fixed(&FixedFields)Method chaining
Encodeoptional fields, apply_nullsEncode and decode
Encodeexact buffer sizing, *EncodedLengthBuffer sizing
EncodeAeron try_claim: Claim, send_fixed, send, OfferClaimAeron try_claim
Decodecomposites, endianness, layoutComposite layout and endianness
Decodeflyweights vs owned structsFlyweight vs whole-struct
Decodechecked entry points, tails checked as reachedTrust boundary
DecodeNullVal and OptionWhy NullVal instead of Option
DecodeDisplay / Debug textDisplay and Debug
Decodeschema descriptions as rustdocSchema descriptions as rustdoc
Configpresets: new, lean, profile(GenerationProfile)GenerationConfig options
Configwith_conversion, with_domain_type, with_manual_domain_type, selectorswith_conversion vs with_domain_type
Configwith_enum_mapping, with_composite_mappingApp types on composites
Configwith_null_as_option, with_all_enums_as_optionOpting into Option
Configwith_bool_domain_typeNull-aware accessors on BooleanType
Configwith_domain_objects(DomainVarData)Domain DTOs
Configcompact_str, smol_str, bytes, chrono featuresFeature integrations
Configtimestamp conversionsTimestamp conversions
Configwith_validateValue validation
Configwith_source_traits, with_encode_version, with_external_sbe_rt, with_module_name, with_keyword_append_token, with_deprecated_attrs, with_display_debug, with_meta_attributes, with_dispatchGenerationConfig options
Extendwith_hook, contexts, accessor names and typesCode-generation hooks
Extendwith_try_hook, GenerateError::HookHooks that can fail
Extendschema extension marks, any attribute, prefixed or notExtension XML
Extendwith_extension_constsEvery mark as a const
Extendexample label and field-pair hooksExample hooks
ExtendConversionSelector::extension_attrExtensionAttr conversions
Extenda venue’s SBE responses rendered as its JSONExchange example
Referencetype-state cost, API freeze, feature matrixType-state, API freeze, Feature matrix
Referencebenchmarks against sbe-toolBenchmarks, Methodology

Exact sizing

Which length API to call is Buffer sizing. This page walks one message: the builder counts the shape, then the encoder writes that many bytes.

#![allow(unused)]
fn main() {
pub fn demo_car_size_and_encode() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    // Fuel: 2 entries with usage ASCII lengths 5 and 7.
    // Performance: 1 entry with 2 nested acceleration rows (fixed-only entries).
    // Message var-data: manufacturer / model / activationCode lengths.
    let complete_len = CarEncoder::compute_length()
        .fuel_figures_ragged(2, |ff| {
            ff.add()?.usage_description(5)?; // "Urban"
            ff.add()?.usage_description(7)?; // "Highway"
            Ok(())
        })?
        .performance_figures_ragged(1, |pf| {
            pf.add()?.acceleration(|acc| {
                acc.uniform(2)?;
                Ok(())
            })?;
            Ok(())
        })?
        .manufacturer(5)? // "Honda"
        .model(9)? // "Civic VTi"
        .activation_code(6)? // "abcdef"
        .encoded_length_with_header();

    // Exact size from compute_length → stack pad (this demo fits well under 512).
    const CAR_PAD: usize = 512;
    assert!(
        complete_len <= CAR_PAD,
        "sample car length {complete_len} exceeds stack pad {CAR_PAD}"
    );
    let mut storage = [0u8; CAR_PAD];
    let written = encode_sample_car(&mut storage[..complete_len])?;
    assert_eq!(
        written, complete_len,
        "CarEncodedLength must equal encoder-produced length"
    );
    Ok(storage[..written].to_vec())
}
/// Encode the canonical sample car into `buf` (must be pre-sized).
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

(This code comes from the sbe-feature-tour sample crate.)

Animation, in words: the L3 order book test fixture has bids with 3 levels (2, 1 and 3 orders), asks with 2 levels (1 and 2 orders) and the symbol "BTCUSDT". book_encoded_length starts at the 17-byte fixed block. bids_ragged(3, …) adds the group header and all three 18-byte level blocks in one step (4 + 3 × 18), because level blocks share a width; each level then adds only its orders with uniform(n) (4 + n × 17), since order counts differ per level. The length reaches 189 after bids, 288 after asks and 299 after the symbol (197, 296 and 307 with the header); encoded_length_with_header() adds the 8-byte header last, giving 307. The builder visits 5 levels, no orders one by one, and touches no buffer. encode_book then writes into vec![0u8; 307] in wire order (header, fixed block, bids to byte 197, asks to 296, symbol to 307), and the test asserts len == actual: no oversizing, no truncation; with one byte less, encode_book returns an error. The cost is a second pass over the levels; the book records no timing for it.

Bulk arrays

For repeating groups with fixed-size entries (no var-data, no nested groups), generated encoders offer a bulk_add(&[Entry]) path that validates the destination region once and writes every entry.

Car fuelFigures has var-data (usageDescription), so it is not eligible. The nested acceleration group is eligible: each row is mph + seconds only:

#![allow(unused)]
fn main() {
pub fn demo_bulk_add() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true);
    let rows = [
        CarPerformanceFiguresAccelerationEntry {
            mph: 30,
            seconds: 4.0,
        },
        CarPerformanceFiguresAccelerationEntry {
            mph: 60,
            seconds: 7.5,
        },
    ];
    let complete_len = CarEncoder::compute_length()
        .fuel_figures_ragged(0, |_| Ok(()))?
        .performance_figures_ragged(1, |pf| {
            pf.add()?.acceleration(|acc| {
                acc.uniform(2)?;
                Ok(())
            })?;
            Ok(())
        })?
        .manufacturer(5)?
        .model(5)?
        .activation_code(3)?
        .encoded_length_with_header();
    const PAD: usize = 256;
    assert!(
        complete_len <= PAD,
        "bulk-add car length {complete_len} exceeds pad {PAD}"
    );
    let mut storage = [0u8; PAD];
    let buf = &mut storage[..complete_len];
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)?
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: *b"ABCDEF",
            extras,
            engine: Engine::new(
                2000,
                4,
                *b"123",
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(0, |_| Ok(()))?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.bulk_add(&rows)?;
                    Ok(())
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic")?
        .activation_code_as_str("abc")?
        .encoded_length_with_header();
    assert_eq!(len, complete_len);
    Ok(buf[..len].to_vec())
}
}

(From samples/sbe-feature-tour, compiled and run in that crate’s tests.)

bids / asks on the l3-book schema have a nested orders group, so those outer groups are not eligible either. Only a leaf group whose entries are a pure fixed block gets bulk_add.

Constants and MetaAttribute expose schema metadata on every generated type (HeartbeatDecoder::sequence_meta_attribute(MetaAttribute::Presence) and friends). See the generated module after cargo build of the feature-tour sample.

Decoder lanes

A decoder with groups or var-data has two jobs: read some fields in any order, or walk the whole message once in schema order. A group decoder from a random-access getter implements Iterator for partial traversal; it is not a third message-decoding lane.

Encoding is one state machine: each stage is the cursor, so the next legal field is the only method on that type. See Encode and decode and Method chaining. Decoding is the choice, because a decoder can be asked to read in an order the encoder never had.

LaneEntryOrderDynamic-tail costSync
Random accesstry_decode / wrap gettersAnyRecalculates preceding offsetsyes
Stagedinto_* / skip_*Compile timeOne forward traversalyes
Ordereddecoder.ordered()Compile timeDelegates to stagedyes
Memoizeddecoder.memoized()AnyCache of discovered boundariesno (Send)

Fixed fields stay random-access in all of them. Ordered also offers a fixed callback (fixed-fields-only view, not the full decoder). A message with no groups and no var-data has one lane: the base decoder. memoized() and ordered() are not generated; AnyMessage offers only into_<name>().

If you want…Use
Some fields, any order, share &DecoderRandom access (default)
Whole message in wire orderStaged into_* / skip_*
Whole message, one callback per tailOrdered (decoder.ordered())
Same decoder, many helpers, mixed tail orderMemoized (benchmark it; not the default)

Animation, in words: the L3 order book test fixture is 307 bytes: fixed block, bids (3 levels, 2/1/3 orders), asks (2 levels, 1/2 orders), then symbol. Reading symbol, bids, asks, symbol in that order, random access walks 14 + 0 + 9 + 14 = 37 entries only to find where tails start, because every getter re-walks from the fixed block. Memoized walks 14 on the first read, publishing the ends of bids (byte 197) and asks (byte 296) to its cache, then hits the cache. Staged walks each entry once as it reads it, but only in wire order: reading symbol first does not compile. Counts come from the generated code; they are not timings.

Worked nested example: L3 order book. AnyMessage can land in a lane directly (into_car(), into_car_memoized()).

sbe-tool has one &mut flyweight with a limit cursor. Wrong order reads the next group’s bytes as a length prefix; re-read means re-wrap; no useful &-sharing. Ergon splits those jobs. Full mapping: Coming from sbe-tool.

In every ergon lane, try_* construction makes a short buffer a DecodeError (not a panic), and a group’s numInGroup is checked against the bytes that are actually there before an entry reaches you.

Random access

Any-order getters. The decoder holds the buffer, offset, and acting header values and nothing else. Each dynamic-tail getter re-walks from the fixed block.

#![allow(unused)]
fn main() {
pub fn demo_car_random_access(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let car = CarDecoder::try_decode(wire, 0)?;
    // Manufacturer is the first var-data field, after both groups, and still legal
    // here because random access rescan preceding tails.
    assert_eq!(car.manufacturer_as_str()?, "Honda");
    assert_eq!(car.serial_number(), 1234);
    let mut speeds = Vec::new();
    for entry in car.fuel_figures()? {
        speeds.push(entry?.speed());
    }
    assert_eq!(speeds, vec![30, 60]);
    assert_eq!(car.model_as_str()?, "Civic VTi");
    Ok(())
}
}

Memoized (decoder.memoized())

Same getter names. First access to a tail walks forward from the cache frontier; later accesses reuse it. Construction is O(1) and allocates nothing. Decoded values match the base lane, including schema max-length rejection: warming the cache with encoded_length() does not accept a payload the base getter would refuse.

let decoder = CarDecoder::try_from(bytes)?;   // small, Sync, recalculates tails
let decoder = decoder.memoized();             // lazy cache, no allocation

read_header(&decoder)?;
read_groups(&decoder)?;
read_final_tail(&decoder)?;                   // reuses discovered boundaries

Build it once and pass &CarMemoizedDecoder. Calling .memoized() inside every function creates a separate empty cache. Cell interior mutability: Send but not Sync. into_inner() returns the base decoder.

The base lane’s tail_offset_k re-walks every preceding tail on every getter, which is quadratic even in schema order. Memoized makes that sweep linear. Staged already carries the cursor, so it needs no cache.

Use it when several helpers read the same decoder, or when you jump to a late tail and come back. Skip it for one tail and stop, a full wire-order walk (use staged), or if you need Sync.

The cache covers message-level tails only. Nested groups inside an entry use an ordinary entry decoder. just bench-diagnostics runs versioned_l3_bench.

Staged (into_* / skip_*)

Sequential decode, the encoder dual. Each into_* consumes the stage. Wrong order is a missing method.

Group entriesinto_<group>Why
Own groups or var-datavisit closure returning the entry’s completionNo stride: the completion is the next offset
Fixed-stride (no tails)iteratorNext entry is offset + acting block length

Iterator is implemented for &mut Iter only, so for entry in iter does not compile, so a loop cannot drop the rest of the message. Also ExactSizeIterator and FusedIterator.

#![allow(unused)]
fn main() {
pub fn demo_car_decode_stages(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let car = CarDecoder::try_decode(wire, 0)?;
    assert_eq!(car.serial_number(), 1234);
    assert_eq!(car.model_year(), 2013);
    // Domain conversion: BooleanType → bool when configured.
    let available: bool = car.available()?;
    assert!(available);
    assert_eq!(car.code(), Model::A);
    assert_eq!(car.discounted_model(), Model::C); // constant field
    assert_eq!(car.engine().capacity(), 2000);

    // Schema order: groups then var-data, one chain. Both of Car's groups have
    // entries that carry their own tails, so both take a visit closure: the
    // completion the closure returns is where the next entry starts, so the
    // group is walked exactly once.
    let mut speeds = Vec::new();
    let mut octanes = Vec::new();
    let (mfr, decoder) = car
        .into_fuel_figures(|entry| -> Result<_, sbe_rt::DecodeError> {
            speeds.push(entry.speed());
            // usageDescription is this entry's only tail, so reading it
            // completes the entry.
            entry.into_usage_description().map(|(_usage, done)| done)
        })?
        .into_performance_figures(|entry| -> Result<_, sbe_rt::DecodeError> {
            octanes.push(entry.octane_rating());
            // acceleration has fixed-stride entries, so it is a real iterator.
            let mut accel = entry.into_acceleration()?;
            assert_eq!((&mut accel).len(), 2);
            accel.finish()
        })?
        .into_manufacturer_as_str()?;
    assert_eq!(speeds, vec![30, 60]);
    assert_eq!(octanes, vec![95]);
    let (model, decoder) = decoder.into_model_as_str()?;
    let (code, _decoder) = decoder.into_activation_code_as_str()?;
    // All three &str coexist: each borrows 'a from the original wire buffer.
    assert_eq!((mfr, model, code), ("Honda", "Civic VTi", "abcdef"));
    Ok(())
}
}

Each into_*_as_str() returns (&'a str, NextStage<'a>); the &str borrows the original buffer. See Method chaining.

Start with try_decode / try_from. Do not verify first then walk: that is two structural passes. Inside a dynamic-entry callback, consume nested tails with into_* / skip_* / ordered() and return that completion. Random-access getters or a root manufacturer_len() before visiting preceding groups rescan.

Consuming stages and group iterators are #[must_use]. Dropping a stage without into_* / skip_* / finish() abandons remaining tails.

A fixed-stride iterator need not be drained: finish(), or the next tail’s into_* / skip_* on the iterator, skips unread entries as count × block_length. Dynamic-stride skip_* still walks each unread entry.

Asking before walking

AccessorAnswersWhere
<group>_count()Result<usize, DecodeError>base, .memoized(), stage before the group, nested entries
<field>_len()var-data byte length, same Resultsame four places
iter.remaining_entries()unread entries (usize)the group iterator

Absent versioned tails are 0. If a primary getter already uses that name, the convenience accessor is omitted on that owner. Non-consuming is not constant-time on random-access owners, because lookahead may scan preceding tails. Group byte length is not available from the count when entries have tails.

#![allow(unused)]
fn main() {
pub fn demo_car_visit_entries(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let car = CarDecoder::try_decode(wire, 0)?;

    // Non-advancing: `car` is untouched and still owns every tail.
    assert_eq!(car.fuel_figures_count()?, 2);
    assert_eq!(car.manufacturer_len()?, 5);

    // A fixed-stride group is a real iterator, and it does not have to be
    // drained. Read one acceleration entry, then let the walk move on: the
    // unread entries are skipped by the next step, not lost.
    let (mfr, _rest) = car
        .skip_fuel_figures()?
        .into_performance_figures(|entry| -> Result<_, sbe_rt::DecodeError> {
            let mut accel = entry.into_acceleration()?;
            assert_eq!((&mut accel).len(), 2);
            let first = (&mut accel).next().expect("acceleration is not empty");
            assert_eq!(first.mph(), 30);
            assert_eq!(accel.remaining_entries(), 1);
            // `finish()` skips the entry we did not read and completes.
            accel.finish()
        })?
        .into_manufacturer_as_str()?;
    assert_eq!(mfr, "Honda");
    Ok(())
}
}

Prefer staged when you skip tails, hold stages across functions, or want for entry in &mut iter. A closure error consumes the stage; there is no continuation to retry.

Ordered (decoder.ordered())

One callback per tail, same spelling at message and nested-entry level, plus EntryInfo per entry. Generated on message decoders with tails and on group entries that carry tails. An entry whose existing accessor is named ordered keeps that accessor and does not get this lane.

ordered() is sbe_rt::Ordered<S> over the staged stage, with no second cursor. A nested ordered() walk is the completion the parent callback owes. .done() only unwraps the staged complete. The message chain ends on encoded_length_with_header() / as_bytes_with_header(), like encode.

#![allow(unused)]
fn main() {
pub fn demo_car_ordered_lane(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let mut speeds = Vec::new();
    let mut octanes = Vec::new();
    let mut text = Vec::new();

    let len = CarDecoder::try_decode(wire, 0)?
        .ordered()
        .fixed(|car| {
            assert_eq!(car.serial_number(), 1234);
            Ok(())
        })?
        .fuel_figures(|entry, info| {
            // `info` carries the position the wire declares.
            assert_eq!(info.count, 2);
            assert_eq!(info.is_last(), info.index == 1);
            speeds.push(entry.speed());
            Ok(entry.ordered().usage_description(|_| Ok(()))?)
        })?
        .performance_figures(|entry, _info| {
            octanes.push(entry.octane_rating());
            Ok(entry.ordered().acceleration(|a, _| {
                let _ = (a.mph(), a.seconds());
                Ok(())
            })?)
        })?
        .manufacturer_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .model_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .activation_code_as_str(|s| {
            text.push(s.to_owned());
            Ok(())
        })?
        .encoded_length_with_header();

    assert_eq!(speeds, vec![30, 60]);
    assert_eq!(octanes, vec![95]);
    assert_eq!(text, vec!["Honda", "Civic VTi", "abcdef"]);
    assert_eq!(len, wire.len());
    Ok(())
}
}
TailCallback
Fixed blockfixed(|&{Name}DecoderFixedView|)
Group, entries with tailsgroup(|entry, EntryInfo|), returning the entry completion, or Ordered<completion> from nested ordered()
Group, fixed-stridegroup(|entry, EntryInfo|), returning ()
Var-datafield(|&[u8]|), and field_as_str(|&str|) when the schema declares text encoding

EntryInfo is index, wire-declared count, acting block_length, plus is_first() / is_last() / remaining(). No entry scan. Group byte length is absent: entries with tails only settle it by traversing.

Message-level fixed is optional. Skip it, or call it and lose the view. The view has no group/var-data accessors. A first tail named fixed owns the fixed() name, so the fixed-block callback yields: read fixed fields before ordered(). Every callback returns Result<_, DecodeError>; a caller error type converts after the walk. Entry-level wrappers have no fixed: the parent already holds the entry.

Empty and version-absent groups invoke the callback zero times. <group>_count() on the ordered stage reports the wire-declared count for an empty group and 0 for a group the wire version predates, which has no count.

Bytes and text callbacks borrow 'a from the original buffer. A callback error consumes the stage. Prefer ordered when you always decode whole messages and want one shape. Prefer staged to skip, hold stages, or iterate.

Full-frame bytes mid-walk

NeedAPI
Full frame after the walkcomplete stage as_bytes_with_header()
Full frame without consuming stagesinherent dec.as_bytes_with_header()? (rescans tails)
Fixed block onlydec.get_metadata().as_fixed_region_with_header()?

See Generated code.

What generated code looks like

For a schema with one message (Car), ergo-sbe emits a single Rust module with:

Decoder (flyweight over &[u8])

// Each message gets a zero-allocation decoder.
pub struct CarDecoder<'a> {
    pub(crate) buf: &'a [u8],
    pub(crate) offset: usize,
    pub(crate) acting_version: u16,
    pub(crate) acting_block_length: usize,
}

impl<'a> CarDecoder<'a> {
    // Illustrative only: real values come from your schema.
    pub const SCHEMA_ID: u16 = 1;
    pub const TEMPLATE_ID: u16 = 1;
    pub const BLOCK_LENGTH: usize = 45;
    pub const HEADER_LENGTH: usize = 8;

    // Checked framed entry (message start). Validates header + fixed extent.
    pub fn try_decode(buf: &'a [u8], pos: usize)
        -> Result<Self, sbe_rt::DecodeError> { ... }

    // Proves the header+fixed-body extent and panics if short.
    // Caller does not need `unsafe`: the proof is in the constructor.
    pub fn wrap(buf: &'a [u8], message_offset: usize,
               acting_block_length: usize, acting_version: u16)
        -> Self { ... }

    // Full dynamic-tail structural check (associated, not `car.verify()`).
    pub fn verify(buf: &[u8]) -> Result<(), sbe_rt::VerifyError> { ... }

    // Fixed fields are random-access: zero-copy reads after a checked wrap.
    #[inline]
    pub fn serial_number(&self) -> u64 {
        let offset = self.offset + 0;
        u64::from_le_bytes(/* private read after extent proof */)
    }
}

Encoder (type-state stages)

// Wire order is enforced by named stage types. The root encoder also carries a
// fields-state parameter: tails are reachable only after `fixed()`.
pub struct CarEncoder<
    'a,
    H: sbe_rt::HeaderState = sbe_rt::HeaderPresent,
    F: sbe_rt::FieldsState = sbe_rt::FieldsUnfixed,
> { ... }
pub struct CarAfterFuelFigures<'a, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent> { ... }
pub struct CarAfterPerformanceFigures<'a, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent> { ... }
pub struct CarComplete<'a, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent> { ... }

// `fixed()` moves FieldsUnfixed -> FieldsFixed; the tail methods exist only on
// the fixed phase, so `wrap(...).fuel_figures(...)` is a compile error.
pub type CarUnfixedEncoder<'a, H = sbe_rt::HeaderPresent> =
    CarEncoder<'a, H, sbe_rt::FieldsUnfixed>;

impl<'a, H: sbe_rt::HeaderState> CarEncoder<'a, H, sbe_rt::FieldsUnfixed> {
    pub fn fixed(self, fixed: &CarFixedFields) -> CarEncoder<'a, H, sbe_rt::FieldsFixed> { ... }
}

// Calling stages out of order is a type error: `CarEncoder` has no `asks()`.
impl<'a, H: sbe_rt::HeaderState> CarEncoder<'a, H, sbe_rt::FieldsFixed> {
    pub fn fuel_figures(self, count: u16, f: impl FnOnce(...) -> ...) -> Result<CarAfterFuelFigures> { ... }
}
impl<'a, H: sbe_rt::HeaderState> CarAfterFuelFigures<'a, H> {
    pub fn performance_figures(self, ...) -> Result<CarAfterPerformanceFigures> { ... }
}
impl<'a, H: sbe_rt::HeaderState> CarComplete<'a, H> {
    pub fn encoded_length_with_header(&self) -> usize { ... }
}
// Only when the header is in the buffer:
impl<'a> CarComplete<'a, sbe_rt::HeaderPresent> {
    pub fn as_bytes_with_header(&self) -> &[u8] { ... }
}

Metadata: no field-name collisions

Utility methods like remaining, buffer, as_bytes_with_header, and as_body_bytes live on a zero-copy metadata struct from get_metadata(). A schema field named remaining or buffer therefore generates dec.remaining() / dec.buffer() as field accessors, with no _field suffix.

Reserved decoder names (ordered, memoized, acting_version, acting_block_length, …) still rename a colliding message-level field (ordered_field()). Group entries do not rename against that list: if an entry field is actingVersion, it keeps acting_version() and the metadata getter is omitted.

Convenience accessors (<group>_count, <field>_len, ordered fixed) yield to a same-named tail or field; the primary getter wins. A domain-typed field counts: its getter takes the plain field name (renamed against the same reserved list), so orders_count beside a group orders stays the field. reserved_name_clash_test, ordered_lane_test.

What does remaining() mean?

Receiverremaining() means
Group decoder (e.g. FuelFiguresDecoder)Entry count left (usize), not bytes
dec.get_metadata() / enc.get_metadata()Byte slice after the acting fixed block (&[u8])
Schema field named remainingOrdinary field accessor (natural name, no rename)

Session framing (header then app payload) must use get_metadata().remaining() for the payload bytes.

let dec = CarDecoder::try_decode(&buf, 0)?;
dec.serial_number();                              // field accessor, never collides
dec.get_metadata().remaining();                   // metadata, never collides
dec.get_metadata().buffer();                      // metadata, never collides
// Car has groups/var-data: metadata is fixed-block only (not a full frame).
dec.get_metadata().as_fixed_region_with_header()?;
// Complete frame after walking tails, or rescan without consuming:
// complete.as_bytes_with_header() / dec.as_bytes_with_header()?
dec.encoded_length_with_header()?;                // hot path stays on base struct

The metadata struct holds a reference to the parent (zero-copy):

pub struct CarDecoderMetadata<'m, 'a> {
    decoder: &'m CarDecoder<'a>,
}

Encoders have the same pattern. Fixed-only messages expose as_body_bytes / as_bytes_with_header only after fixed(&FixedFields) (on the encoder and on FieldsFixed metadata). Messages with tails use as_fixed_body_bytes / as_fixed_region_with_header until the complete stage.

let meta = enc.get_metadata();
meta.as_fixed_body_bytes();            // fixed block only when message has tails
meta.as_fixed_region_with_header();    // header + fixed block, not the full frame
meta.message_offset();                 // message start in buffer

Metadata limits (tailed messages)

APISpanFull Car frame?
meta.limit()body start + acting block lengthNo: stops at fixed block end
meta.as_fixed_region_with_header()?header + acting fixed blockNo
meta.remaining()bytes after that fixed endMay still include unread tails of this message
complete stage as_bytes_with_header()header through last var-dataYes (after walking tails)
dec.as_bytes_with_header()? (inherent rescan)same full frame without consuming stagesYes (rescans tails)

Do not use meta.limit() as the next-message offset in a multi-message buffer for Car-shaped schemas, because it truncates at the fixed block.

acting_version / acting_block_length (dual surface)

These remain inherent on the message decoder for the hot path (dec.acting_version(), dec.acting_block_length()) and are also exposed on metadata (dec.get_metadata().acting_version()) for a uniform placement facet. Both paths return the same values. They are reserved method names: a schema field named actingVersion becomes acting_version_field on the decoder.

Exact buffer sizing

// Fixed-only messages: const length.
let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];

// Variable-length: staged builder (zero allocation).
let len = CarEncoder::compute_length()
    .fuel_figures_ragged(1, |ff| {
        ff.add()?.usage_description(5)?;
        Ok(())
    })?
    .performance_figures_ragged(0, |_| Ok(()))?
    .manufacturer(5)?
    .model(9)?
    .activation_code(6)?
    .encoded_length_with_header();

Configuration controls output size

Every aspect of generated output is configurable:

GenerationConfig::new("msgs")
    .with_display_debug(false)   // omit Debug/Display impls
    .with_meta_attributes(false) // omit *_ENCODING_OFFSET etc.
    .with_dispatch(false)        // omit AnyMessage/FrameCursor
    .with_domain_objects(DomainVarData::Bytes) // owned DTOs

A default single-message schema with these knobs off produces minimal output.

GenerationConfig::new enables display/debug, metadata, and dispatch, and disables domain objects, deprecated attributes, blanket enum options, and automatic bool mapping. GenerationProfile::Lean turns off the three output-heavy conveniences (display/debug, metadata, dispatch). See the canonical option table.

Real example

The sbe-feature-tour sample builds and exercises a real Car schema. Run cargo test inside that directory to see the generated API in action, or open src/generated/feature_tour.rs after cargo build.

Trust boundaries

Checked entry points validate the message header and fixed block. verify walks the complete dynamic tail before bulk access:

#![allow(unused)]
fn main() {
pub fn demo_try_vs_trusted(valid_car: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    // `decode` validates template_id, schema_id, version, and the
    // version-aware fixed body extent at message start (offset 0).
    let _dec = CarDecoder::try_decode(valid_car, 0)?;

    // `verify` walks the complete dynamic tail (groups + var-data), not a
    // header-only peek. Use it when you need full structural acceptance
    // without materialising a long-lived decoder stage chain.
    CarDecoder::verify(valid_car)?;

    // Truncated buffers fail checked entry points with Result errors.
    assert!(
        CarDecoder::try_decode(&valid_car[..8.min(valid_car.len())], 0).is_err(),
        "truncated buffer should fail try_decode"
    );
    if valid_car.len() > 16 {
        assert!(
            CarDecoder::verify(&valid_car[..16]).is_err(),
            "truncated buffer should fail verify (incomplete tail)"
        );
    }

    // `wrap` still returns Result and validates the body extent given acting
    // block_length + version (message start, not sbe-tool body offset).
    let mut hdr_bytes = [0u8; 8];
    hdr_bytes.copy_from_slice(&valid_car[..8]);
    let hdr = MessageHeader(hdr_bytes);
    let dec = CarDecoder::try_wrap(valid_car, 0, hdr.block_length() as usize, hdr.version())?;
    assert_eq!(dec.serial_number(), 1234);
    Ok(())
}
}

(This code comes from the sbe-feature-tour sample crate.)

Where the tiers are specified

Checked try_*, trusted bare wrap / decode, and unsafe *_unchecked are specified once, with the encoder and decoder tables, in Trust boundary. Prefer try_decode when every failure, including a short buffer, must be a Result. sbe-tool offsets: Coming from sbe-tool.

The constructor is the trust checkpoint. After a safe constructor proves the header and the version-aware fixed extent, field accessors do not re-check that extent. Dynamic tails still check when they are read. Use *_unchecked only after an independent extent proof.

Domain objects (DTOs)

Latency-sensitive paths: never use DTOs. Domain objects allocate (Vec, String) and copy every field out of the wire buffer. If latency matters, use the zero-copy flyweight decoder instead. DTOs are for tooling, logging, and offline processing, not the hot path.

with_domain_objects builds that owned struct. It is not with_domain_type. Borrowed view versus owned snapshot: Flyweight vs whole struct. with_conversion versus with_domain_type: with_conversion vs with_domain_type. Which groups re-encode in bulk from the DTO, and the encode/decode recipe: Domain DTOs.

This fixture uses DomainVarData::Strings:

#![allow(unused)]
fn main() {
pub fn demo_car_domain_dto(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let dec = CarDecoder::try_decode(wire, 0)?;
    // try_from_decoder (not TryFrom/From): two fallible sources, decoder vs
    // try_from_slice_with_header for framed bytes; materialisation can fail.
    let dto = CarDomain::try_from_decoder(dec)?;
    assert_eq!(dto.serial_number, 1234);
    assert!(dto.available); // bool domain field
    assert_eq!(dto.fuel_figures.len(), 2);
    assert_eq!(dto.fuel_figures[0].usage_description, "Urban");
    assert_eq!(dto.manufacturer, "Honda");

    const RE_PAD: usize = 512;
    assert!(wire.len() <= RE_PAD);
    let mut storage = [0u8; RE_PAD];
    let n = dto.encode(&mut storage[..wire.len()])?;
    assert_eq!(&storage[..n], wire, "DTO re-encode must be byte-identical");
    Ok(())
}
}

(This code comes from the sbe-feature-tour sample crate.)

Multi-template dispatch

AnyMessage reads the generated header layout and dispatches on the template ID. Prefer AnyMessage::try_decode at untrusted boundaries (returns Result). Bare AnyMessage::decode is the same implementation today; keep using try_* naming for consistency with the three-tier trust boundary.

#![allow(unused)]
fn main() {
pub fn demo_any_message() -> Result<(), Box<dyn std::error::Error>> {
    let mut hb = [0u8; HeartbeatEncoder::compute_length_with_header()];
    let hb_len = HeartbeatEncoder::compute_length_with_header();
    let nanos: u64 = 1_700_000_000_000_000_000;
    let _hb_len = HeartbeatEncoder::try_wrap_and_apply_header(&mut hb, 0)
        .unwrap()
        .fixed(&HeartbeatFixedFields {
            sequence: 1,
            timestamp: nanos,
        })
        .encoded_length_with_header();

    let note_body = "hello AnyMessage";
    let note_len = NoteEncoder::compute_length_with_header(note_body.len());
    const NOTE_PAD: usize = 64;
    assert!(note_len <= NOTE_PAD);
    let mut note_storage = [0u8; NOTE_PAD];
    let note = &mut note_storage[..note_len];
    let note_written = NoteEncoder::try_wrap_and_apply_header(note, 0)?
        .fixed(&NoteFixedFields { note_id: 99 })
        .body_as_str(note_body)?
        .encoded_length_with_header();
    assert_eq!(note_written, note_len);

    // Concatenate framed messages (each includes its own SBE header).
    let mut stream = Vec::new();
    stream.extend_from_slice(&hb[..hb_len]);
    stream.extend_from_slice(&note[..note_written]);

    let mut offset = 0usize;
    let mut saw_heartbeat = false;
    let mut saw_note = false;
    while offset < stream.len() {
        match AnyMessage::try_decode(&stream, offset)? {
            AnyMessage::Heartbeat(d) => {
                assert_eq!(d.sequence(), 1);
                offset += d.encoded_length_with_header()?;
                saw_heartbeat = true;
            }
            AnyMessage::Note(d) => {
                assert_eq!(d.note_id(), 99);
                let (body, complete) = d.into_body_as_str()?;
                assert_eq!(body, note_body);
                offset += complete.encoded_length() + NoteDecoder::HEADER_LENGTH;
                saw_note = true;
            }
            AnyMessage::Car(_) => return Err("unexpected Car in this demo stream".into()),
            AnyMessage::Quote(_) => return Err("unexpected Quote in this demo stream".into()),
            AnyMessage::Unknown { .. } => {
                return Err("unexpected Unknown template".into());
            }
        }
    }
    assert!(saw_heartbeat && saw_note);
    Ok(())
}
}

(This code comes from the sbe-feature-tour sample crate.)

Core concepts

Trust boundary

Every SBE buffer crossing a process boundary must be validated. This page is the only full statement of the three constructor tiers. The feature tour shows the calls on a buffer and does not repeat these tables.

TierPrefixBehaviour on bad bufferUse case
Checkedtry_{wrap,decode,…}Returns Result::ErrUntrusted input, process boundaries
Trustedbare name (wrap, decode, …)Panics after the same extent proof. Bare decode still returns Err on a wrong template or schemaKnown-good buffers
Uncheckedunsafe fn *_uncheckedUB (raw pointer ops). decode_unchecked still returns Err on a wrong template or schemaProven-tight hot loops

The ladder, from untrusted bytes to typed fields:

flowchart LR
    B["untrusted bytes"] --> W["wrap / decode"]
    W --> Z["private zero-check core"]
    Z --> G["typed getters / setters"]
    U["*_unchecked: skip the proof"] -.->|"UB on OOB, not the default"| W

try_* returns Result::Err; bare names panic after the same extent proof; decode is the hybrid above. *_unchecked is not shipped as a default path; use it only after an independent extent proof.

Wire layout follows official SBE offsets and order for the shapes under test (compatibility profile); official SBE wire compatibility outranks API convenience.

The trusted tier is safe Rust. Bare constructors run the same buffer extent proof as try_*, then panic on failure. try_* additionally rejects a declared block length below the version floor — a validity check verify shares — while the trusted tier takes the caller’s word that the frame is well-formed. After that proof, field accessors/setters use unchecked loads/stores (justified by the constructor). Dynamic tails still check on consume.

try_decode does not first traverse all dynamic tails. A staged walk validates them as it advances, so checked construction is compatible with a single-pass decoder. A separate verify() before that walk adds another structural pass. Checks for text encoding happen when text accessors are used.

The unsafe fn *_unchecked variants skip the extent proof entirely, only for the case where panic machinery is measurable and the caller has proven the layout independently.

Fixed extent across schema versions

The header’s acting version tells the decoder which fields the sender knows. Its acting block length tells it how many fixed-body bytes precede the first tail. The local BLOCK_LENGTH describes the generated schema, so it cannot replace the sender’s length when locating a tail.

Checked construction requires acting_block_length to be at least min_readable_fixed_extent(acting_version) — raised to the compiled BLOCK_LENGTH when the acting version is the current schema version or a newer one (extensions only append), so schema-declared padding stays part of the frame — and the body to hold acting_block_length bytes. verify() applies the same floor, so the two agree on which frames are acceptable. An older frame can therefore have a shorter fixed block than the local schema. The floor counts required fields only: an optional field the block does not reach reads as absent (None, NullVal, the empty set, the composite’s null image or a zero-filled array), never past the block. An optional boolean’s *_bool getter returns Err(InvalidBoolean) instead, so a domain DTO rejects such a frame. A compatible newer frame can have an unknown fixed suffix, which the decoder skips before reaching the existing tails. This does not make arbitrary schema edits compatible: keep the official SBE evolution rules and the published compatibility profile.

In words: an illustrative v2 decoder knows an 8-byte v1 fixed block and a 4-byte optional field added in v2. With an 8-byte header, a v1 frame’s first tail starts at byte 16 and the absent v2 field returns None. A v2 frame’s tail starts at byte 20. A compatible v3 frame adds an unknown 4-byte fixed suffix: the decoder proves all 16 declared body bytes fit, reads its known fields and starts the tail at byte 24. A frame claiming 12 body bytes but containing only 8 is rejected by try_decode before any decoder is returned. These are illustrative append-only layouts, not a feature-tour wire fixture. Successful construction still leaves dynamic-tail and value checks to their respective walks.

Dynamic tails are checked as reached

Animation, in words: an illustrative 79-byte frame (8-byte header, 16-byte fixed block, a fixed-stride group of 17-byte entries) has a group header that claims numInGroup 1000 but holds bytes for 3 entries. try_decode, decode and decode_unchecked differ only at the message’s own header and fixed-body proof (Err, panic, or UB if short); here that body is real, so all three succeed. Reaching the group runs the same checks in every tier: the 4-byte group header fits, numInGroup ≤ u32::MAX, the short-block rule (a positive count needs blockLength ≥ the 17 bytes its getters read), then 1000 × 17 = 17000 bytes needed against 51 left: Err(BufferTooShort) before any entry decoder exists, after reading 4 bytes and one multiply. A blockLength of 0 with a positive count passes the product (1000 × 0 = 0) but fails the short-block rule. verify and skip_<group> use the same product; random access to a later tail walks the group entry by entry and fails at the fourth. A group with nested groups or var-data has no fixed stride, so each entry is proven as it is reached and the first three are yielded before the error. No timing is recorded for these checks.

A var-data length above its length type’s maxValue is malformed even when the buffer holds every byte. Reading the field rejects it with InvalidVarDataLength on every lane, and so do the paths that prove a whole message or entry: verify, encoded_length, as_body_bytes, a staged read or skip_<group>, skip_n, ordered() and the memoized lane. On those the maximum is checked before the buffer length, so a huge length in a short buffer reports InvalidVarDataLength, not BufferTooShort. A random-access read that only passes over an earlier field to reach a later one, group iteration and scan_entry_at check bounds only: the later read succeeds, and the over-max field is rejected when it is read. The memoized lane is the exception: it proves every boundary it caches, so its getter for a later field also rejects an earlier over-max one.

Value validation (opt-in)

The tiers above prove bounds, not values. A frame from an older or foreign producer can be in bounds and still carry a value the schema does not allow. Generate with GenerationConfig::with_validate(true) to get validate() on every message decoder, group entry decoder and AnyMessage. Call it after try_decode, which still checks bounds only: NewOrderDecoder::try_decode(buf, 0)?.validate()? returns the first sbe_rt::ValidateError.

Wire valueValidateError
integer or char scalar, or integer array element, outside a declared minValue / maxValueValueOutOfRange
enum discriminant that is neither a validValue nor the enum’s nullUnknownEnum
set bit that no choice declaresUnknownSetBits
AnyMessage::UnknownUnknownTemplate
malformed group or var-data tailDecode

validate() reads every field and every group entry, so keep it off the hot path (archive replay, ingest from another team’s producer). It does not allocate. Not checked: bounds the schema does not declare, floats, fixed char arrays (NUL padding is valid SBE) and var-data contents. An optional field’s null value passes. DecodeError is unchanged.

Encoder entry points

EntryReturnBehaviour
Encoder::try_wrap(buf, offset)Result<Encoder, EncodeError>Validates capacity, returns Err
Encoder::wrap(buf, offset)Encoder (body-only)Panics if header+fixed body do not fit
Encoder::try_wrap_and_apply_header(buf, pos)Result<Encoder, EncodeError>Validates capacity + writes header, returns Err
Encoder::wrap_and_apply_header(buf, pos)Encoder (header written)Panics if header+fixed body do not fit
unsafe fn Encoder::wrap_unchecked(buf, offset)Encoder (body-only)UB on OOB (raw pointer setters)
unsafe fn Encoder::wrap_and_apply_header_unchecked(buf, pos)Encoder (header written)UB on OOB (copy_nonoverlapping header)

Decoder entry points

EntryReturnBehaviour
Decoder::try_wrap(buf, offset, bl, ver)Result<Decoder, DecodeError>Validates body extent, returns Err
Decoder::try_decode(buf, pos)Result<Decoder, DecodeError>Header + template/schema + version-aware fixed extent (all failures are Err)
Decoder::wrap(buf, offset, bl, ver)DecoderPanics if version-aware fixed body does not fit
Decoder::decode(buf, pos)Result<Decoder, DecodeError>Hybrid: panics if short; Err on wrong template/schema only
unsafe fn Decoder::wrap_unchecked(buf, offset, bl, ver)DecoderUB on OOB (raw pointer accessors)
unsafe fn Decoder::decode_unchecked(buf, pos)Result<Decoder, DecodeError>Unchecked extent (UB on OOB) + checked identity (Err on wrong template/schema)

Why decode returns Result but still panics

Bare decode keeps a freeze-friendly hybrid so feed handlers can ? on WrongTemplate / WrongSchema after demux, while short buffers remain a trusted-tier panic (same extent proof as wrap). Prefer try_decode when every failure, including short buffers, must be a Result.

See Trust boundaries (feature tour) for worked examples.

Wire order via named stages

SBE is positional: groups and var-data appear in a fixed schema order with no per-field tags. Two nearly identical groups back-to-back (bids then asks) are common. Swap them and the bytes still look valid; prices land on the wrong side of the book. That mistake is a type error here, not a production incident.

sbe-tool uses .parent() to hand encoder ownership back up the tree. In Rust that fights the borrow checker. ergo-sbe uses scoped closures so nested schemas stay readable:

#![allow(unused)]
fn main() {
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

(From sbe-feature-tour; compiles and runs in CI.)

Order is the type-state pattern, implemented as named concrete stage structs (CarAfterFuelFigures), not Encoder<State>. The H: HeaderState generic on every stage is a zero-sized marker for header-present vs body-only. It does not track wire-order. Duplicating the stage graph for HeaderPresent / HeaderAbsent would provide no latency advantage.

pub struct BookEncoder<'a> { /* buf, msg_offset, offset, … */ }
pub struct BookAfterBids<'a> { /* same layout */ }
pub struct BookAfterAsks<'a> { /* same layout */ }

impl BookEncoder<'a> {
    pub fn bids(self, …) -> Result<BookAfterBids<'a>, …> { … }
    // no asks(): bids come first on the wire
}
impl BookAfterBids<'a> {
    pub fn asks(self, …) -> Result<BookAfterAsks<'a>, …> { … }
}

Animation, in words: the sample Car above is 142 bytes. Wrapping the buffer writes the 8-byte header, checks once that header and fixed block (53 bytes) fit, and sets offset to 53. The type is CarEncoder with F = FieldsUnfixed, whose only way forward is fixed() (its field setters return &mut Self and never change the type); calling fuel_figures first fails with rustc’s E0599, whose note says the method exists on CarEncoder<'a, H, FieldsFixed>. fixed() writes the 45-byte fixed block with no bounds checks and returns the same struct with F = FieldsFixed. Calling performance_figures before fuel_figures also fails with E0599, naming the type you hold. fuel_figures(2, …) writes a 4-byte group header and two entries (15 and 17 bytes); each add closure must return CarFuelFiguresEntryComplete, which only usage_description_as_str produces. A count check then moves the value into CarAfterFuelFigures. performance_figures (21 bytes, with a nested group), manufacturer, model and activation_code follow, each returning the next type, ending in CarComplete at byte 142. Only CarComplete has as_bytes_with_header. Every stage is the same 32 bytes on a 64-bit target (slice pointer and length, msg_offset, offset, plus zero-sized markers): no tag, no branch. The cost is one forward pass in wire order, with group counts declared up front. Byte and check counts come from the generated code; they are not timings.

After fixed fields you may only call the next group or var-data. BookEncoder has no asks method. Decoders use the same idea (BookDecoder, then BookDecoderAfterBids, and so on).

Group bodies use |g| { g.add(|e| { … }) }: the closure ends, then chaining continues. See Type-state and Benchmarks for the cost claim and the 1.00× gate.

Buffer Sizing

This page is the only copy of the sizing rule table. The samples guide links here.

Aeron try_claim (and similar slots) needs the encoded size before you write. Guessing with vec![0u8; 4096] and copying later defeats that model.

Describe the shape (group counts, nested groups, var-data lengths) and get an exact size from the generated API:

Message shapeGenerated sizingPrefer
Fixed only{Msg}Encoder::compute_length_with_header() (const)stack / claim of that length
Groups / nested / ragged{Msg}EncodedLength staged builderlen then encode into a claim/slot of len

MAX_ENCODED_LENGTH counts one entry per group and only var-data that declares maxLength, so it is an upper bound only for a message with no groups whose var-data all declare maxLength. After writing, assert that the computed length equals the encoded length.

flowchart LR
    S["shape: group counts and var lengths"] --> L["exact encoded length"]
    L --> C["try_claim of that many bytes"]
    C --> E["encode into the claim"]
#![allow(unused)]
fn main() {
pub fn demo_car_size_and_encode() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    // Fuel: 2 entries with usage ASCII lengths 5 and 7.
    // Performance: 1 entry with 2 nested acceleration rows (fixed-only entries).
    // Message var-data: manufacturer / model / activationCode lengths.
    let complete_len = CarEncoder::compute_length()
        .fuel_figures_ragged(2, |ff| {
            ff.add()?.usage_description(5)?; // "Urban"
            ff.add()?.usage_description(7)?; // "Highway"
            Ok(())
        })?
        .performance_figures_ragged(1, |pf| {
            pf.add()?.acceleration(|acc| {
                acc.uniform(2)?;
                Ok(())
            })?;
            Ok(())
        })?
        .manufacturer(5)? // "Honda"
        .model(9)? // "Civic VTi"
        .activation_code(6)? // "abcdef"
        .encoded_length_with_header();

    // Exact size from compute_length → stack pad (this demo fits well under 512).
    const CAR_PAD: usize = 512;
    assert!(
        complete_len <= CAR_PAD,
        "sample car length {complete_len} exceeds stack pad {CAR_PAD}"
    );
    let mut storage = [0u8; CAR_PAD];
    let written = encode_sample_car(&mut storage[..complete_len])?;
    assert_eq!(
        written, complete_len,
        "CarEncodedLength must equal encoder-produced length"
    );
    Ok(storage[..written].to_vec())
}
/// Encode the canonical sample car into `buf` (must be pre-sized).
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

(From sbe-feature-tour: EncodedLength + exact buffer encode, tested in CI.)

Nested books: book_encoded_length. API matrix: encoded_length_api_test.

Flyweight vs whole struct

Use the style that matches how much of the message you touch.

The first decision is ownership: can your work finish while the input buffer is borrowed, or must the decoded message outlive that buffer? A flyweight is a view into the frame. An owned DTO copies values and owns its dynamic data. FixedFields is a convenience for encoding a fixed block, not a DTO containing the decoded groups and var-data.

In words: a borrowed CarDecoder reads serial_number directly from the frame without collecting groups or copying text. Reaching var-data may still require walking or skipping earlier tails. CarDomain::try_from_decoder instead walks the message, copies its fixed values and collects owned groups and text; that work can fail and can allocate. After borrowed views end, the input buffer can be reused. The owned DTO retains its old values independently. The animation uses the feature-tour Car with DomainVarData::Strings; its tiles summarise data rather than show byte offsets.

StyleBest whenCostSchema evolution
Flyweight (per-field)You only read one or a few fields; hot pathBorrowed frame; no whole-message copy or heap allocationYou can leave new fields unread; version and block-length guards determine field availability
*FixedFields + .fixed(...)You always write the entire fixed blockOne struct write, still flyweight bufferAdding a required fixed field to the schema is a compile error until you set it in the struct
*Domain DTO (.with_domain_objects(DomainVarData::…))Whole message as owned data; enum picks String vs Vec<u8> var-dataAllocates, so never use it on the hot path. Easier app code for tooling, logging, offline processingSame idea: regenerating after a schema change forces you to fill new struct fields
*Source trait (.with_source_traits(true))Encode your own type, groups and var-data included, without a DTONo allocation: groups are iterators, var-data is borrowedA new field is a new trait method: every implementation stops compiling until it provides it

Encode: whole fixed block as a struct

When you always populate every fixed field, a struct is clearer, and schema additions break at compile time:

#![allow(unused)]
fn main() {
let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
// Buffer is exact size from const compute_length_with_header — no bounds check needed.
let len = HeartbeatEncoder::try_wrap_and_apply_header(&mut buf, 0)?
    .fixed(&HeartbeatFixedFields { sequence: 7, timestamp: 0 })
    .encoded_length_with_header();
let dec = HeartbeatDecoder::try_from(&buf[..len])?;
assert_eq!(dec.sequence(), 7);
}

(From book/examples/heartbeat-encode.rs, compiled against the feature-tour codec.)

If the schema later adds a required field to the fixed block, this stops compiling until you add it to the struct literal, so you cannot silently omit it.

Decode: individual fields (flyweight)

#![allow(unused)]
fn main() {
// Encode a sample car first (normally bytes come from the wire)
let complete_len = CarEncoder::compute_length()
    .fuel_figures_ragged(0, |_| Ok(()))?
    .performance_figures_ragged(0, |_| Ok(()))?
    .manufacturer(5)?
    .model(5)?
    .activation_code(3)?
    .encoded_length_with_header();
const PAD: usize = 256;
assert!(complete_len <= PAD, "car length {complete_len} exceeds pad {PAD}");
let mut storage = [0u8; PAD];
let buf = &mut storage[..complete_len];
let fields = CarFixedFields {
    serial_number: 1234,
    model_year: 2013,
    available: true.into(),
    code: Model::A,
    some_numbers: [10, 20, 30, 40],
    vehicle_code: *b"ABCDEF",
    extras: OptionalExtras::default(),
    engine: Engine::new(2000, 4, *b"123", 0i8, false.into(), Booster::new(BoostType::TURBO, 210)),
};
let n = CarEncoder::try_wrap_and_apply_header(buf, 0)?
    .fixed(&fields)
    .fuel_figures(0, |_| Ok(()))?
    .performance_figures(0, |_| Ok(()))?
    .manufacturer_as_str("Honda")?
    .model_as_str("Civic")?
    .activation_code_as_str("abc")?
    .encoded_length_with_header();
assert_eq!(n, complete_len);
// Now decode — read only the fields you need, no DTO allocation:
let car = CarDecoder::try_from(&buf[..n])?;
assert_eq!(car.serial_number(), 1234);
assert_eq!(car.model_year(), 2013);
assert_eq!(car.code(), Model::A);
assert_eq!(car.engine().capacity(), 2000);
}

(From book/examples/flyweight-access.rs, compiled against the feature-tour codec.)

Decode: whole message as a DTO

Do not use on the latency-sensitive path. DTO decode allocates Vec/String and copies every field. For the hot path, use the flyweight decoder instead.

When you always need (almost) everything, or want to pass a value across threads / into non-SBE code:

#![allow(unused)]
fn main() {
pub fn demo_car_domain_dto(wire: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let dec = CarDecoder::try_decode(wire, 0)?;
    // try_from_decoder (not TryFrom/From): two fallible sources, decoder vs
    // try_from_slice_with_header for framed bytes; materialisation can fail.
    let dto = CarDomain::try_from_decoder(dec)?;
    assert_eq!(dto.serial_number, 1234);
    assert!(dto.available); // bool domain field
    assert_eq!(dto.fuel_figures.len(), 2);
    assert_eq!(dto.fuel_figures[0].usage_description, "Urban");
    assert_eq!(dto.manufacturer, "Honda");

    const RE_PAD: usize = 512;
    assert!(wire.len() <= RE_PAD);
    let mut storage = [0u8; RE_PAD];
    let n = dto.encode(&mut storage[..wire.len()])?;
    assert_eq!(&storage[..n], wire, "DTO re-encode must be byte-identical");
    Ok(())
}
}

Encode: your own type through a Source trait

*FixedFields covers the fixed block only. With .with_source_traits(true) each message gets a {Message}Source trait with one getter per field in wire order, impl ExactSizeIterator<Item = impl …EntrySource> per repeating group, &[u8] per var-data, and the encoder gains encode_from(&src) and encoded_length_with_header_from(&src). Implement the trait on the type your application already has; encode_from writes it through the same setters and type-state stages a hand-written encode uses, and returns the terminal stage:

#![allow(unused)]
fn main() {
/// The application's own type: no generated struct is involved.
struct Reminder {
    id: u32,
    text: String,
}

impl NoteSource for Reminder {
    fn note_id(&self) -> u32 {
        self.id
    }
    fn body(&self) -> &[u8] {
        self.text.as_bytes()
    }
}

let reminder = Reminder { id: 9, text: "settle T+1".into() };
let len = NoteEncoder::encoded_length_with_header_from(&reminder)?;
let mut scratch = vec![0u8; len];
let claim = sbe_rt::OfferClaim::new(&mut scratch, |_: &[u8]| -> Result<(), &'static str> { Ok(()) });
NoteEncoder::send(claim, |enc| enc.encode_from(&reminder))?;
}

(From book/examples/claim-send.rs, compiled against the feature-tour codec.)

A fixed getter returns what the field’s *FixedFields entry holds (Option<T> for an optional field, whose None writes the null value and whose Some of the null value, NaN for a float, is refused as SomeNullValue), or its domain type when one is configured. A group iterator whose len() does not match what it yields is GroupCountMismatch or GroupFull, as with a hand-written group.

Rule of thumb: for one field on the hot path, use the flyweight. If you always fill or consume the whole message, use FixedFields / Domain for clarity and compile-time breakage on schema growth. More on DTOs in Recipes: Domain DTOs.

Composite layout and endianness

On a little-endian host, can a composite be a #[repr(C)] / #[repr(C, packed)] overlay so field access is a free load?

Almost, but not via repr(C) transmute. ergo-sbe does something safer that is still a plain load on LE:

ApproachWhat ergo-sbe doesWhy not the other thing
Wire image#[repr(transparent)] pub struct Engine(pub [u8; 10]): the value is the on-wire bytes#[repr(C)] native fields insert alignment padding; SBE is packed and may be unaligned
Accessorsfrom_le_bytes / to_le_bytes at schema offsetsNative loads break big-endian schemas and unaligned safety
FlyweightEngineDecoder { buf, offset } reads in placeDefault decode path
Eager valueengine_value() copies the N-byte image onceStill not field-by-field re-pack; .0 is the wire block
EncodeWriter copies engine.0 into the frameSame image the decoder reads back

On LE hosts, from_le_bytes lowers to a load. The generator also emits

const _: () = assert!(core::mem::size_of::<Engine>() == 10);

so the Rust type size is locked to the wire size.

Animation, in words: the feature-tour Engine packs capacity (2 bytes), numCylinders, a 3-byte manufacturer code, efficiency, boosterEnabled and a 2-byte Booster into 10 bytes; the constants maxRpm and fuel take none. Engine.0 holds those bytes (d0 07 04 31 32 33 23 01 4e c8 in the test fixture), and capacity() reads bytes 0–1 with from_le_bytes (2000); a big-endian schema would store 07 d0 and use from_be_bytes. A #[repr(C)] Engine happens to have the same offsets but needs 2-byte alignment, so a #[repr(C)] Car block pads before it: engine moves from byte 35 to 36 and the block grows from 45 to 48 bytes, so an overlay would read capacity from 07 04 (1031). The encoder copies engine.0 to frame bytes 43–52 (header 8 + 35, an odd offset); the flyweight EngineDecoder reads capacity from bytes 43–44 in place, and engine_value() copies all 10. Sizes and offsets come from the generated code and composite_layout_test; the big-endian bytes are illustrative.

*FixedFields is an application struct used to fill the fixed block in one call. It is not a zero-copy overlay; .fixed(&…) writes each field with endian conversion.

Single-field access is already one load. layout_access_bench compares flyweight, preheld [u8; N], and #[repr(C, packed)] on a mid-block field: they measure equivalently. Materialising the whole composite first is the expensive path. zerocopy FromBytes/IntoBytes was evaluated and was not faster than the flyweight mov.

You need…Use
One or a few fields on the hot pathFlyweight
Whole composite as an owned wire blobValue Engine([u8; N]) / *_value(); pay N once
Hand-rolled repr(C, packed) for speedSkip it: same cost, extra UB/layout risk

We do not generate packed field structs: packing, unaligned references, big-endian schemas, enums/sets/nested composites. The transparent wire image is the portable form that already optimizes to the packed load on LE.

On encode, encode_style_bench shows .fixed(&CarFixedFields{…}) and individual setters measure equivalently after inlining. Prefer .fixed for completeness, not speed. Building a BE image on an LE host costs a bswap per multi-byte field; once the image exists, write cost matches LE.

composite_layout_test · layout_access_bench · encode_style_bench. Read live Criterion output; do not quote numbers from this page.

Configuration

Wire type vs app type

The full comparison is with_conversion vs with_domain_type.

NameRole
Decimal (schema composite)Wire: generated type / price_value(), what is in the buffer
Cents, rust_decimal::Decimal, …App: what your code wants to use
  app  ──price_from / price(v)──►  wire Decimal on the buffer
  buf  ──price_as / price()──►    app value

Feature integrations

Optional Cargo features. Enable them on both [build-dependencies] and [dependencies]; the generator decides what to emit from its own feature set.

FeatureBest for
compact_strTickers / symbols / venue codes in DTOs (≤24 B inline)
smol_strLong-lived DTOs that clone often
bytesRelay / forwarding, shared buffers
chronoTyped timestamps on encode/decode
[build-dependencies]
ergo-sbe = { version = "0.1", features = ["compact_str", "chrono"] }

[dependencies]
ergo-sbe = { version = "0.1", features = ["compact_str", "chrono"] }

Measure with var_data_types_bench / chrono_converter_bench rather than quoting numbers from this page. DTO materialisation is never the hot path.

CompactString

Primarily for domain DTOs. Replaces String with compact_str::CompactString (≤24 bytes on the stack). The codec also gains into_<field>_as_compact_str() on text var-data stages.

use ergo_sbe::{DomainVarData, GenerationConfig};

let config = GenerationConfig::new("msgs")
    .with_domain_objects(DomainVarData::CompactStrings);
pub struct QuoteDomain {
    pub symbol: ergo_sbe::compact_str::CompactString,
    pub venue: ergo_sbe::compact_str::CompactString,
    pub price: Decimal,
}
let (symbol, _next_stage) = L3BookDecoder::try_decode(wire, 0)?
    .skip_bids()?
    .skip_asks()?
    .into_symbol_as_compact_str()?;

SmolStr

O(1) clone regardless of length. DomainVarData::SmolStrings plus into_<field>_as_smol_str().

let config = GenerationConfig::new("msgs")
    .with_domain_objects(DomainVarData::SmolStrings);

Bytes

Reference-counted buffer. DomainVarData::BytesCrate plus into_<field>_as_bytes().

let config = GenerationConfig::new("relay")
    .with_domain_objects(DomainVarData::BytesCrate);
let original = bytes::Bytes::copy_from_slice(b"payload");
let clone = original.clone();
let sub = original.slice(4..);
let (payload, next) = stage.into_payload_as_bytes()?;

Chrono

Schema fields are typically uint64 with a timestamp semanticType. The converters take i64. Map them with with_domain_type (only DateTime<Utc> is built in; for NaiveDateTime you write TryFromSbe<u64> and TryToSbe<u64>):

use ergo_sbe::{GenerationConfig, ConversionSelector};

let config = GenerationConfig::new("msgs")
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestamp"),
        "chrono::DateTime<chrono::Utc>",
    )
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestampMicros"),
        "chrono::NaiveDateTime",
    );
let created: chrono::DateTime<chrono::Utc> = dec.created_at()?;
let updated: chrono::NaiveDateTime = dec.updated_at()?;
enc.created_at(chrono::Utc::now())?;
enc.updated_at(chrono::DateTime::from_timestamp(1_720_000_000, 0).unwrap().naive_utc())?;

One semantic_type("UTCTimestamp") covers every field with that attribute. Worked example: Timestamps.

Direct converters (chrono feature):

use ergo_sbe::chrono_converters::*;

let dt = i64_nanos_to_datetime(1_720_000_000_000_000_000);
let ns = datetime_to_i64_nanos(dt);
let naive = i64_micros_to_naive(1_720_000_000_000_000);
assert_eq!(naive_to_i64_micros(naive), 1_720_000_000_000_000);

Combining

[build-dependencies]
ergo-sbe = { version = "0.1", features = ["compact_str", "bytes", "chrono"] }

[dependencies]
ergo-sbe = { version = "0.1", features = ["compact_str", "bytes", "chrono"] }
let config = GenerationConfig::new("msgs")
    .with_domain_objects(DomainVarData::CompactStrings)
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestamp"),
        "chrono::DateTime<chrono::Utc>",
    );

with_conversion vs with_domain_type

This is the only full comparison of with_conversion and with_domain_type. An owned DTO (with_domain_objects) is a different switch: Domain objects, Domain DTOs, Flyweight vs whole struct.

Do not call both for the same selector: a domain type already enables conversion.

A: with_conversionB: with_domain_type
IdeaGeneric convert API; you plug in any app typeAlways use this Rust path
build.rs.with_conversion(named_type("Decimal")).with_domain_type(…, "rust_decimal::Decimal")
You writeTryFromSbe<Decimal> / TryToSbe<Decimal> for your typeUsually nothing for bool / rust_decimal / chrono
Decodelet p: Cents = dec.price_as()?let p: rust_decimal::Decimal = dec.price()?
Encodeenc.price_from(&cents)?enc.price(rust_decimal::Decimal::new(12345, 2))?
Raw wireprice_value() / price_wire(...)same when conversion is active
Sampleexchange-example · demo_conversion_onlyl3-book

Which fields a selector reaches, and what shape you get

A selector matches by precedence (exact FieldPath, then SemanticType, then an ExtensionAttr schema mark, then NamedType), so a blanket mapping plus one per-field override behaves the way it reads, whatever order you register them in. Paths are "Message.field", extended with group names inside a group ("Order.legs.price").

extension_attr("exponent") selects fields whose schema carries a namespaced exponent attribute (any prefix); extension_attr_value("exponent", "price") additionally requires that exact value. Marks select fields only — the Rust type always comes from build.rs, never from the schema. ExtensionAttr reaches message and group fields (nested group entries included); marks on <data>, <group> elements and type-level declarations are visible to hooks only.

named_type matches a composite, enum or set by name, or a primitive alias: with <type name="Timestamp" primitiveType="uint64"/>, named_type("Timestamp") selects every field declared type="Timestamp", in messages and groups. It never matches a bare primitive (uint64).

A selector that cannot apply fails generation instead of being skipped:

ConfigGenerateError
field_path / semantic_type / extension_attr that matches no fieldInvalidConversion: “matches no field in the schema”
named_type naming no composite, enum or set, and no alias a field usesInvalidConversion: “no matching type found in schema”
with_domain_type / with_manual_domain_type twice on one selector, different typesInvalidConversion: “mapped to both A and B”
a domain-type selector whose every field a higher-precedence selector takesInvalidConversion: “every field it matches takes a higher-precedence selector”
two extension domain selectors tie on one field with different typesInvalidConversion: “ambiguous extension selectors for field …”
with_null_as_option on anything but named_type(<enum>)InvalidConfiguration

When the schema has names close to an unknown one, the reason ends (did you mean …?) with up to three of them.

generate_multi resolves each selector against the union of its schemas. A later with_enum_mapping / with_composite_mapping for the same type still replaces an earlier one.

What the accessor gives you depends on the field’s shape, because it mirrors the raw accessor it delegates to:

Fieldwith_conversionwith_domain_type
Required, sinceVersion=0price_as::<T>() -> Result<T, _>price() -> Result<T, _>
sinceVersion > 0Result<Option<T>, _>Result<Option<T>, _>
presence="optional" scalarResult<Option<T>, _>Result<Option<T>, _>

The Option layer means “no value on the wire”: absent at this version, or the schema null value. It is never used to report a bad value; an invalid wire value is the Err.

Composites, enums, and sets all take domain types. Fixed arrays and optional scalars keep their wire type in a domain DTO even when a selector matches them. The flyweight still gets the converted accessor, but the owned struct stores [u8; N] / Option<i64>.

1 · Match
2 · Rank
3 · Validate
4 · Accessor shape
field_path(p) · FieldPath
p equals the path: "Message.field", or "Order.legs.price" in a group
semantic_type(s) · SemanticType
s equals the field’s semanticType
extension_attr(a) · ExtensionAttr
the field carries schema extension attribute a, any namespace; extension_attr_value(a, v) also needs value v. Message and group fields only.
named_type(n) · NamedType
n equals a composite, enum or set name, or a primitive field’s <type> alias. named_type("uint64") matches nothing: a bare built-in has no name.
Lowest rank wins
0 · FieldPath
1 · SemanticType
2 · ExtensionAttr
3 · NamedType
whatever order the selectors were registered in
field_path, semantic_type or extension_attr matching no field: “matches no field in the schema”
named_type naming nothing: “no matching type found in schema”
one selector, two domain types: “mapped to both A and B”
a domain type path that is empty or not a valid Rust type
a domain-type selector whose every field a higher-ranked one takes
two extension_attr domain types tying on one field: “ambiguous extension selectors for field F”
Fixed array
never Option: Result<T, _> (zero-filled when the field predates the version)
Scalar primitive
Result<Option<T>, _> if sinceVersion > 0 or presence="optional", else Result<T, _>
Enum
Result<Option<T>, _> if sinceVersion > 0 or with_null_as_option maps it, else Result<T, _>
Composite or set
Result<Option<T>, _> if sinceVersion > 0, else Result<T, _>
Both selectors match Quote.price: its type is the Decimal composite, and its path is "Quote.price".
FieldPath (0) beats NamedType (3): Quote.price takes the field_path mapping. Other Decimal fields keep the named_type one.
If field paths take every Decimal field, as in the book’s example schema (only Quote.price), a domain-type named_type has none left: “every field it matches takes a higher-precedence selector”.
Quote.price is a composite: the domain getter price() returns Result<T, _> (T from field_path), or Result<Option<T>, _> if its sinceVersion > 0.
one predicate per selector
precedence
each failure: GenerateError::InvalidConversion
what f_as::<T>() or domain f() returns
None means no value on the wire; an invalid wire value is the Err.
Worked example: named_type("Decimal") and field_path("Quote.price") as domain types, in a schema with more Decimal fields
Conversion selectors: which selector wins a field, and what its accessor returns

Option A: you choose the app type (Cents)

#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // A — generic converter: one wire type, many app types
    let _cfg =
        GenerationConfig::new("msgs").with_conversion(ConversionSelector::named_type("Decimal"));
}

(From book/examples/conversion-config.rs, a self-contained program that compiles against ergo-sbe.)

#![allow(unused)]
fn main() {
use rust_decimal::Decimal as Rd;
// App adapter: wire Decimal ↔ rust_decimal::Decimal
struct FixedPrice { mantissa: i64, exponent: i8 }

impl TryFromSbe<Decimal> for FixedPrice {
    type Error = &'static str;
    fn try_from_sbe(wire: Decimal) -> Result<Self, Self::Error> {
        Ok(FixedPrice {
            mantissa: wire.mantissa(),
            exponent: wire.exponent(),
        })
    }
}
impl TryToSbe<Decimal> for FixedPrice {
    type Error = &'static str;
    fn try_to_sbe(&self) -> Result<Decimal, Self::Error> {
        Ok(Decimal::new(self.mantissa, self.exponent))
    }
}
}

(From book/examples/conversion-app-code.rs: the app adapter pattern, compiled against tour_codec.)

// Encode using the generic conversion API:
let mut buf = [0u8; QuoteEncoder::compute_length_with_header()];
let price = Rd::new(12345, 2); // 123.45
let mut enc = QuoteEncoder::try_wrap_and_apply_header(&mut buf, 0)?;
enc.price_from(&price)?;
enc.size_from(&Rd::new(10, 0))?;
let len = QuoteEncoder::compute_length_with_header();
// Decode — generic `_as::<T>()` picks your adapter:
let dec = QuoteDecoder::try_from(&buf[..len])?;
let p: Rd = dec.price_as()?;
assert_eq!(p, Rd::new(12345, 2));
// Same buffer, different app type — only possible with with_conversion:
let fixed: FixedPrice = dec.price_as()?;
assert_eq!(fixed.mantissa, 12345);
assert_eq!(fixed.exponent, -2);

(Same file: generic _from/_as encode/decode with with_conversion.)

Option B: one fixed app type

#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // B — concrete mapping: one Rust type per wire type (already enables conversion)
    let _cfg = GenerationConfig::new("msgs").with_domain_type(
        ConversionSelector::named_type("Decimal"),
        "rust_decimal::Decimal",
    );
}

(Same source file, book/examples/conversion-config.rs.)

Under with_domain_type the accessors are concrete: price(value)? writes and price()? reads, with no price_from or price_as for that field.

Both styles on different fields:

pub fn demo_conversion_only() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut buf = [0u8; QuoteEncoder::compute_length_with_header()];

    let price = Rd::new(12345, 2); // 123.45
    let size = Rd::new(10, 0);
    let mut enc = QuoteEncoder::try_wrap_and_apply_header(&mut buf, 0)?;
    enc.price_from(&price)?;
    enc.size_from(&size)?;
    let len = QuoteEncoder::compute_length_with_header();

    let dec = QuoteDecoder::try_from(&buf[..len])?;
    let wire = dec.price_value();
    assert_eq!(wire.mantissa(), 12345);
    assert_eq!(wire.exponent(), -2);

    let price2: Rd = dec.price_as()?;
    let size2: Rd = dec.size_as()?;
    assert_eq!(price2, price);
    assert_eq!(size2, size);

    // Same buffer, different app type, only possible with with_conversion.
    let fixed: FixedPrice = dec.price_as()?;
    assert_eq!(
        fixed,
        FixedPrice {
            mantissa: 12345,
            exponent: -2
        }
    );

    let dto = QuoteDomain::try_from_decoder(dec)?;
    assert_eq!(dto.price.mantissa(), 12345);
    let mut re = [0u8; QuoteEncoder::compute_length_with_header()];
    let n = dto.encode(&mut re)?;
    assert_eq!(&re[..n], &buf[..len]);
    Ok(buf[..len].to_vec())
}

(This code comes from the sbe-feature-tour sample crate.)

Option B, manual impl: concrete signatures, your own conversion logic

with_domain_type(selector, path) is the common case: ergo-sbe also generates the TryFromSbe/TryToSbe impl for bool / rust_decimal::Decimal / chrono::DateTime<Utc>. If you need different conversion behaviour for one of those exact three types (a custom rounding rule, stricter validation, different null handling), call additive with_manual_domain_type instead: same generated price(...)? / price()? signatures, but you write the impl:

    let (_schema, src) = generate_domain_with(&path, "manual_impl_dt", |c| {
        c.with_manual_domain_type(
            ergo_sbe::ConversionSelector::named_type("Decimal"),
            "rust_decimal::Decimal",
        )
    });
        use rust_decimal::Decimal;

        // Caller-supplied impl: deliberately scales mantissa by 10 on the way
        // in/out, so a value round-trips only through this impl, which
        // proves ergo-sbe did not generate its own.
        impl TryFromSbe<self::Decimal> for rust_decimal::Decimal {
            type Error = &'static str;
            fn try_from_sbe(wire: self::Decimal) -> Result<Self, Self::Error> {
                Ok(rust_decimal::Decimal::new(wire.mantissa() / 10, (-wire.exponent()) as u32))
            }
        }
        impl TryToSbe<self::Decimal> for rust_decimal::Decimal {
            type Error = &'static str;
            fn try_to_sbe(&self) -> Result<self::Decimal, Self::Error> {
                Ok(self::Decimal::new(self.mantissa() as i64 * 10, -(self.scale() as i8)))
            }
        }

        let mut buf = [0u8; 256];
        let mut enc = OrderEncoder::wrap_and_apply_header(&mut buf, 0)
            .fixed(&OrderFixedFields { price: self::Decimal::new(0, 0), size: self::Decimal::new(0, 0) });
        enc.price(Decimal::new(12345, 2))?;
        enc.size(Decimal::new(100, 0))?;
        let encoded = enc.as_bytes_with_header().to_vec();

        let dec = OrderDecoder::try_decode(&encoded, 0)?;
        assert_eq!(dec.price()?, Decimal::new(12345, 2));
        assert_eq!(dec.size()?, Decimal::new(100, 0));

(From domain_type_manual_impl_uses_callers_own_impl in sbe/tests/baseline_test.rs, a real generated-and-compiled test. Any rust_type string that isn’t one of the three built-ins never gets an auto-generated impl regardless of DomainImpl; the setting only matters for opting those three in or out.)

If you forget the impl, two things soften it. First, the compile error names the missing impl directly instead of the default trait-bound message:

error[E0277]: `rust_decimal::Decimal` has no `TryFromSbe<Decimal>` impl
  |
  | missing `impl TryFromSbe<Decimal> for rust_decimal::Decimal`
  |
  = note: if this field uses DomainImpl::Manual, the generated domain
          accessor's doc comment has a ready-to-paste starting point

Second, for the three built-ins, that pointer is real: the generated price method’s own doc comment (visible on hover, or in cargo doc) carries the exact impl DomainImpl::Generated would have written; copy it out and adjust. sbe/tests/baseline_test.rs’s domain_type_manual_impl_doc_comment_has_generated_snippet asserts this snippet is present in the generated source.

What your domain type must implement

Only Debug. The generated Display/Debug bodies format domain values with {:?}, so a plain #[derive(Debug)] struct works; Display is never required. Note that TryFromSbe::Error / TryToSbe::Error is a separate associated type and does need Debug + Display; &'static str satisfies it.

Option C: generated mappings for enums and composites

When the application type mirrors the SBE type (an enum with the same variants, a struct with the same members), with_enum_mapping and with_composite_mapping generate the TryFromSbe / TryToSbe impls (exhaustive, with renames) and register the domain type in one call. The accessors look exactly like Option B’s. See App Types on Composites.

GenerationConfig options

Every option except new("module_name") is a chained builder method. Boolean flags default to the value shown.

OptionDefaultPurpose
new("module") / lean("module")Full / Leanlean() is new().profile(Lean), with no Display/Debug, meta attrs, or dispatch
with_module_name(name)from newOverride the output module when cloning a base config
with_conversion(selector)noneGeneric *_as::<T>() / *_from(&t) per selected field
with_domain_type(selector, path)noneOne canonical app type per field (implies conversion); Generated impl
with_manual_domain_type(selector, path)noneSame signatures, caller supplies TryFromSbe/TryToSbe
with_enum_mapping(EnumMapping)noneGenerated TryFromSbe/TryToSbe between an SBE enum and your enum, an exhaustive match with renames; NullVal (and an unknown value) is an error (App Types)
with_composite_mapping(CompositeMapping)noneGenerated struct-literal mapping between a composite and your struct, member by member with renames; constants skipped, optional members Option
with_source_traits(enable: bool)false{Message}Source trait per message; encode_from(&src) encodes your own type, groups and var-data included, without allocating
with_validate(enable: bool)falseOpt-in validate() on message decoders, group entries and AnyMessage: declared value ranges, enum discriminants, set bits (sbe_rt::ValidateError; Trust Boundary)
with_domain_objects(var_data)offOwned *Domain + encode; Strings → String (bad UTF-8 → InvalidUtf8), Bytes → Vec<u8>
with_display_debug(enable: bool)trueEmit Debug/Display impls on generated types
with_meta_attributes(enable: bool)trueEmit *_ENCODING_OFFSET, *_ID, *_META_ATTRIBUTE etc.
with_dispatch(enable: bool)trueEmit AnyMessage/FrameCursor/MessageVisitor dispatch
with_bool_domain_type(enable: bool)falseAuto-register bool converters for every boolean enum (name, semanticType, or {0,1} value pair)
with_null_as_option(selector)noneNullVal → None for the enum’s fields; getter returns Option<Enum>. Only named_type(<enum>); any other selector is InvalidConfiguration
with_all_enums_as_option()falseAll enums → Option<Enum>; blanket form of with_null_as_option
profile(GenerationProfile)FullPreset: Full (default conveniences) or Lean (off: Display/Debug, meta attrs, dispatch; domains stay off unless re-enabled). Individual with_* overrides still apply after profile.
with_deprecated_attrs(enable: bool)false#[deprecated(note = "deprecated since schema version N")] on decoder getters of deprecated="N" fields
with_shared_module(name)noneMulti-schema shared types module
with_external_sbe_rt(path)noneShare one sbe_rt runtime module instead of inlining
with_keyword_append_token(token)"_"Schema type → Rust type_
with_encode_version(version)noneEncoder writes version and omits members above it; the decoder still reads every version in the schema
with_hook(fn)noneRegister a code-generation hook (serde, custom traits, …); contexts
with_try_hook(fn)noneA hook that can fail generation: Err(reason) becomes GenerateError::Hook naming the item (hooks)
with_extension_consts(enable: bool)falseEvery schema extension mark (attribute or foreign child element) as a &'static str const next to its item: {Name}Schema::{FIELD}_{ATTR}, {Group}Decoder::{FIELD}_{ATTR}, {Enum}::{VALUE}_{ATTR} (Extension XML)

Selector kinds (field_path, semantic_type, extension_attr, named_type) and their precedence: with_conversion vs with_domain_type.

Turn off with_display_debug, with_meta_attributes, and with_dispatch to shrink generated code. Text fields stay bytes unless the schema declares a character encoding (then strict UTF-8/ASCII helpers apply).

Decoder lanes (no configuration needed)

Memoization is a runtime lane, not a generation knob.

let decoder = CarDecoder::try_from(bytes)?;  // small, Sync, recalculates tails
let decoder = decoder.memoized();            // lazy cache, no allocation

Build it once and share & references. The base decoder is Sync; the memoized one is Send but not Sync. Lanes: Decoder lanes.

Typed error conversions

Implement From on the generated sbe_rt types so ? converts and needed/available survive:

#![allow(unused)]
fn main() {
enum AppError {
    Encode(sbe_rt::EncodeError),
    Decode(sbe_rt::DecodeError),
}

impl From<sbe_rt::EncodeError> for AppError {
    fn from(error: sbe_rt::EncodeError) -> Self {
        match error {
            sbe_rt::EncodeError::BufferTooShort {
                field,
                needed,
                available,
            } => {
                let _ = (field, needed, available);
                Self::Encode(error)
            }
            other => Self::Encode(other),
        }
    }
}

impl From<sbe_rt::DecodeError> for AppError {
    fn from(error: sbe_rt::DecodeError) -> Self {
        Self::Decode(error)
    }
}
}

Code-generation hooks

Niche feature. Hooks are aimed at users who need to attach extra impl blocks to generated code: serde, custom validation, company-internal traits. Most workflows don’t need them; skip this section unless you recognise your use case.

Hooks append tokens after each generated item; they cannot add a #[derive(...)] to the item itself (that attribute would have to precede the struct/enum). Emit the trait impl directly instead; that is what a derive would expand to anyway.

Hooks let you append arbitrary Rust tokens after each generated item (enum, set, composite, message decoder/encoder, group entry decoder, domain struct). The closure receives an ItemContext with structured field/variant/choice metadata, plus a schema reference for full IR access.

Example: add serde Serialize + Deserialize to every enum and set:

// build.rs
use ergo_sbe::{GenerationConfig, ItemContext};
use quote::quote;

fn serde_hook(ctx: &ItemContext) -> Vec<proc_macro2::TokenStream> {
    match ctx {
        ItemContext::Enum { name, variants, .. } => {
            let ident = quote::format_ident!("{name}");
            let labels: Vec<_> = variants.iter().map(|v| v.label.clone()).collect();
            let names: Vec<_> = variants.iter().map(|v| quote::format_ident!("{}", v.name)).collect();
            let from_labels: Vec<_> = variants.iter().map(|v| quote::format_ident!("{}", v.name)).collect();
            vec![quote::quote! {
                impl serde::Serialize for #ident {
                    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                        s.serialize_str(match self {
                            #(Self::#names => #labels,)*
                            _ => "NullVal",
                        })
                    }
                }
                impl<'de> serde::Deserialize<'de> for #ident {
                    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                        let s = <&str>::deserialize(d)?;
                        match s {
                            #(#labels => Ok(Self::#from_labels),)*
                            "NullVal" => Ok(Self::NullVal),
                            // Reject unknown values; fallback is app policy,
                            // not codec behaviour.
                            other => Err(serde::de::Error::unknown_variant(
                                other, &[#(#labels,)* "NullVal"])),
                        }
                    }
                }
            }]
        }
        ItemContext::Set { name, choices, .. } => {
            let ident = quote::format_ident!("{name}");
            let is: Vec<_> = choices.iter().map(|c| quote::format_ident!("is_{}", c.snake_name)).collect();
            let labels: Vec<_> = choices.iter().map(|c| c.label.clone()).collect();
            let froms: Vec<_> = choices.iter().map(|c| quote::format_ident!("{}", c.snake_name)).collect();
            vec![quote::quote! {
                impl serde::Serialize for #ident {
                    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                        let mut names = Vec::new();
                        #(if self.#is() { names.push(#labels); })*
                        names.serialize(s)
                    }
                }
                impl<'de> serde::Deserialize<'de> for #ident {
                    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                        let names: Vec<&str> = <Vec<&str>>::deserialize(d)?;
                        let mut val = Self::default();
                        for n in &names {
                            match *n {
                                #(#labels => { val.#froms(true); })*
                                // Reject unknown labels; don't silently drop.
                                other => return Err(serde::de::Error::unknown_variant(
                                    other, &[#(#labels),*])),
                            }
                        }
                        Ok(val)
                    }
                }
            }]
        }
        _ => vec![],
    }
}

let config = GenerationConfig::new("msgs").with_hook(serde_hook);

Each ItemContext variant carries the fields, variants, or choices defined in the schema; use them to build custom impl blocks or trait implementations. Hooks fire in registration order; the returned tokens are appended after the generated item (so they extend it with impls, not with derives).

Contexts

ContextFiresNames
Enum / Set / Compositeafter the typename, variants / choices / fields
MessageDecoderafter the message decodername (QuoteDecoder), fields, schema_marker (the {Name}Schema type, renamed when a schema type takes the plain name)
GroupEntryDecoderonce per group entry type, nested groups included, depth-first straight after its message decodername (QuoteLegsEntryDecoder), group_decoder (QuoteLegsDecoder), fields, enclosing (the message, then each parent entry, as BlockInfo { decoder, fields })
MessageEncoderafter the encodername, fields
DomainStructafter each DTO, message and entryname, fields

Type names are the generated ones: the message prefix in a multi-message schema and the parent-group prefix of a nested group are already applied. Decoder contexts list fixed fields (constants included, presence == "constant"), then groups, then var-data. Each FieldInfo carries:

FieldValue
name / schema_namesnake_case Rust name / the name as the schema spells it (qtyExponent)
kind, rust_type, offset, presence, since_version, …schema metadata
accessordecoder contexts only: the decoder method returning the field (price, price_wire under a conversion, type_ for a keyword, wrap_field for a reserved name, the domain getter under a domain type)
accessor_typeits exact return type as Rust source (i64, Option<u32>, [u8; 16], Result<QuoteLegsDecoder<'a>, sbe_rt::DecodeError>), read from the generated decoder; may name the decoder’s lifetime 'a, so emit into impl<'a> Decoder<'a>
extensionsthe element’s extension marks

Hooks that can fail

with_try_hook registers a hook returning Result<Vec<TokenStream>, String>. An Err(reason) stops generation with GenerateError::Hook { item, reason }, where item is the context’s kind and generated type name ("GroupEntryDecoder QuoteLegsEntryDecoder"). Plain and try hooks run together in registration order.

#![allow(unused)]
fn main() {
use ergo_sbe::{FieldKind, GenerationConfig, ItemContext};

let config = GenerationConfig::new("msgs").with_try_hook(|ctx: &ItemContext| {
    let ItemContext::GroupEntryDecoder { name, fields, .. } = ctx else {
        return Ok(vec![]);
    };
    if fields.iter().any(|f| f.kind() == FieldKind::Data) {
        return Err(format!("{name}: var-data in a group is not supported here"));
    }
    Ok(vec![])
});
}

Full runnable example with serde + serde_json round-trip: hook_serde_test.

Extension XML on hook contexts

Every ItemContext variant carries the schema extension content of the element it was generated from: namespaced attributes and foreign-namespace child elements that the SBE grammar does not own.

ContextCarries
Enum / Set / Compositethat <enum> / <set> / <composite> element’s own marks
MessageDecoder / MessageEncoderthe <message> element’s marks, foreign children included
GroupEntryDecoderthe <group> element’s marks
DomainStructthe <message> (message DTO) or <group> (entry DTO) element’s marks
EnumVariantInfo / SetChoiceInfothat <validValue> / <choice> element’s marks
FieldInfothat <field> / <group> / <data> element’s marks

Look marks up by local name — any prefix works: extensions.attr("jsonValue"), extensions.child("meta"), extensions.is_empty(). Marks on <data>, <group> elements and type-level declarations reach hooks but are invisible to ConversionSelector::ExtensionAttr, which selects message and group fields only.

Example: emit a JSON label from a jsonValue mark on each variant:

/// Emit `json_label()` for enums whose validValues all carry a `jsonValue`
/// extension mark; enums with partial or no coverage are left untouched, so
/// schemas without marks generate byte-identical code.
fn json_label_hook(ctx: &ergo_sbe::ItemContext) -> Vec<proc_macro2::TokenStream> {
    let ergo_sbe::ItemContext::Enum { name, variants, .. } = ctx else {
        return Vec::new();
    };
    let mut arms = Vec::new();
    for v in variants {
        let Some(label) = v.extensions.attr("jsonValue") else {
            return Vec::new(); // partial coverage: skip the whole enum
        };
        let var = quote::format_ident!("{}", v.name);
        arms.push(quote::quote! { Self::#var => #label, });
    }
    if arms.is_empty() {
        return Vec::new();
    }
    let ident = quote::format_ident!("{name}");
    // Generated enums carry a `NullVal` variant, hence the wildcard arm.
    vec![quote::quote! {
        impl #ident {
            pub fn json_label(&self) -> &'static str {
                match self { #(#arms)* _ => "UNKNOWN" }
            }
        }
    }]
}

The exchange sample applies exactly this hook to its venue schema — exchange example.

Capture rules, the consts switch, the example label and field-pair hooks and ExtensionAttr selectors: Extension XML.

Extension XML

Schema annotations the SBE grammar does not own (extension attributes and foreign-namespace child elements) reach the generator as Extensions on the parse-time Token/Ir. Three generic ways use them, none of which knows any attribute name:

WayWhat you writeWhat you get
with_extension_consts(true)nothingevery mark as a &'static str const next to its item
Hooks (with_hook, with_try_hook)a closure over ItemContextany code: label methods, field pairs, renderers
ConversionSelector::extension_attra selectora domain type or conversion on marked fields

With none opted in, generated code is byte-identical (the empty golden diff is the gate), and no way touches an encoder, a setter or the wire.

What is captured

Every schema node keeps its own marks, matched local-name first: any prefix works (venue:jsonValue, ext:jsonValue), and so does no prefix.

Grammar attributes are read only without a prefix, as sbe-tool reads them. A prefixed grammar name (x:offset, x:blockLength, x:presence) is a mark like any other: it never changes layout or code, whatever its position, and nothing warns about it.

On the schemaCaptured as
Namespaced attribute (x:scaleBy="priceScale")ExtensionAttr { local_name, namespace, value }, document order
Unprefixed attribute the grammar does not define (scale="2")the same, with namespace: None
Foreign-namespace child elementExtensionElement { local_name, namespace, attributes, text, elements }, the whole subtree, text verbatim
xmlns… declarationsnever captured

On <messageSchema>, <message>, <field>, <group> and <data>, two kinds of unprefixed attribute are rejected as typos rather than captured: a grammar attribute the element does not take (blockLength on a <field>) and a near-miss of any grammar attribute (presense, semanticTpye, primitivType: within one edit per four letters). The type-level elements (<types>, <type>, <composite> and its members, <enum>, <validValue>, <set>, <choice>, <ref>) reject neither: a typo there is accepted, as a mark where the element keeps marks (and so as a const with with_extension_consts). A child element in the SBE namespace is always grammar, so a misspelt sbe:enumm fails; an unnamespaced unknown child element fails too.

How other tools treat marks:

CheckPrefixed mark (x:scale)Unprefixed mark (scale)
ergo-sbe parsecapturedcaptured
validate_against_sbe_xsd / with_xsd_validationacceptedrejected, except the sbe-tool extensions it allows (unit on a top-level <type>, jsonValue on <validValue> and <choice>) and where it does not check attributes: composite members and anything inside a <group>
the official sbe.xsd (xmllint --schema)rejectedrejected
sbe-toolXSD-checked only with -Dsbe.validation.xsd, then rejectedthe same

Use a namespace prefix when the schema must pass with_xsd_validation.

Look marks up with attr (any prefix), attr_in (exact namespace URI), child and is_empty; an extension element also exposes text():

#![allow(unused)]
fn main() {
use ergo_sbe::{ExtensionAttr, Extensions};

let ext = Extensions {
    attributes: vec![ExtensionAttr {
        local_name: "exponent".into(),
        namespace: Some("urn:example".into()),
        value: "priceExponent".into(),
    }],
    elements: vec![],
};
assert_eq!(ext.attr("exponent"), Some("priceExponent"));
assert_eq!(ext.attr_in("urn:example", "exponent"), Some("priceExponent"));
assert!(!ext.is_empty());
}

Grammar attributes (name, id, semanticType, …) are not copied into Extensions; read them off the Token’s own fields.

Every mark as a const

GenerationConfig::with_extension_consts(true) emits each extension attribute and each foreign child element (its text, then each of its attributes, then its own foreign children the same way) as an associated &'static str, named in upper snake case:

Mark onConst
<message>{Name}Schema::{ATTR}
message <field>, <group>, <data>{Name}Schema::{FIELD}_{ATTR}
<field>, <group>, <data> inside a group{Group}Decoder::{FIELD}_{ATTR}
<enum>, <set>, <composite>{Type}::{ATTR}
<validValue>, <choice>, composite member{Type}::{VALUE}_{ATTR}
foreign child <x:meta source="a">primary</x:meta>…::META = "primary", …::META_SOURCE = "a"
nested foreign child <x:meta><x:origin desk="b">feed</x:origin></x:meta>…::META_ORIGIN = "feed", …::META_ORIGIN_DESK = "b"
#![allow(unused)]
fn main() {
use ergo_sbe::GenerationConfig;

// <field name="maxQty" x:exponent="qtyExponent" x:jsonPath="limit"/> in
// message MaxAssetFilter gives MaxAssetFilterSchema::MAX_QTY_EXPONENT ==
// "qtyExponent" and MaxAssetFilterSchema::MAX_QTY_JSON_PATH == "limit".
let config = GenerationConfig::new("msgs").with_extension_consts(true);
}

Values are the schema’s own strings, never parsed. A const name that is already on its type fails generation with GenerateError::InvalidConfiguration rather than emitting a duplicate: two marks that spell one name (one local name in two namespaces, a repeated child element), a mark that spells a const the generator emits there (x:templateId on a <message> gives TEMPLATE_ID), or an <enum> mark that spells one of its variants. A mark whose name has no ASCII letter or digit (x:é) fails the same way, since it maps to no const name. Two generated or hook consts that share a name on one type, with or without the switch (a field named template gives TEMPLATE_ID), fail generation with GenerateError::NameClash. Repeats under different cfgs or on different instantiations of a generic type (impl G<u8>, impl G<u16>, or generic impls such as impl<T> H<T, u8>, impl<T> H<T, u16>) generate, as rustc accepts them. Repeats the check cannot see (a type alias, cfgs that can both hold such as cfg(test) and cfg(all(test))) are left to rustc.

Hooks on extension marks

A hook receives the marks of every node it can see on ItemContext; every captured node reaches one:

Captured nodeHook context
messageSchema root, <types>, includesany context, through schema.ir.extensions
<enum> / <validValue>Enum { extensions, variants[].extensions }
<set> / <choice>Set { extensions, choices[].extensions }
<composite> / memberComposite { extensions, fields[].extensions }
<message> and its foreign childrenMessageDecoder / MessageEncoder { extensions }
message-level <field> (constants included), <group>, <data>MessageDecoder.fields[]
<group> elementGroupEntryDecoder { extensions }, once per entry type, nested groups included
fields, nested <group>, <data> inside a group, any depthGroupEntryDecoder.fields[]
a group entry’s enclosing blocksGroupEntryDecoder.enclosing[]: the message, then each parent entry

Decoder contexts name the generated code a hook emits against, so it never re-derives a rule: each FieldInfo has schema_name (as the schema spells it, which is what a mark naming another field holds), accessor (the decoder method: price_wire under a conversion, type_ for a keyword, the domain getter under a domain type) and accessor_type (its exact return type, read from the generated decoder). MessageDecoder.schema_marker names the {Name}Schema type; GroupEntryDecoder gives the entry and group decoder type names. Registration, with_try_hook and the field table: Code-generation hooks.

Example hooks

sbe/tests/common/ext_recipes.rs holds venue-neutral hooks: ergo-sbe’s tests use it, the exchange sample’s build.rs includes it, and the code below is quoted from it. Copy and change it freely; it is not ergo-sbe API. Attribute and method names come from the caller.

Labels: labels("jsonValue", "json_value") adds fn json_value(self) -> &'static str to every enum or set with at least one marked value. The built-in as_str and Display keep the variant name.

/// `attr` on enum values or set choices -> `pub const fn {method}(self) -> &'static str`.
///
/// Emitted only for a type at least one of whose values carries `attr`. An
/// unmarked enum value gives its variant name and `NullVal` gives `"NullVal"`;
/// an unmarked set choice gives its schema name, and a set word that is not
/// exactly one choice gives `"UNKNOWN"`.
pub fn labels(
    attr: &'static str,
    method: &'static str,
) -> impl Fn(&ItemContext) -> Out + Send + Sync + 'static {
    move |ctx| {
        let (ty, body) = match ctx {
            ItemContext::Enum { name, variants, .. }
                if variants.iter().any(|v| v.extensions.attr(attr).is_some()) =>
            {
                let arms = variants.iter().map(|v| {
                    let var = format_ident!("{}", v.name);
                    let label = v.extensions.attr(attr).unwrap_or(&v.name);
                    quote! { Self::#var => #label, }
                });
                let body = quote! { match self { #(#arms)* Self::NullVal => "NullVal" } };
                (ident(name)?, body)
            }
            ItemContext::Set { name, choices, .. }
                if choices.iter().any(|c| c.extensions.attr(attr).is_some()) =>
            {
                let arms = choices.iter().map(|c| {
                    // The match runs on the set word: one bit per choice.
                    let word = 1u128.checked_shl(c.bit_position.into()).unwrap_or(0);
                    let word = Literal::u128_unsuffixed(word);
                    let label = c.extensions.attr(attr).unwrap_or(&c.label);
                    quote! { #word => #label, }
                });
                let body = quote! { match self.0 { #(#arms)* _ => "UNKNOWN" } };
                (ident(name)?, body)
            }
            _ => return Ok(vec![]),
        };
        let method = ident(method)?;
        let doc = format!("Label from the schema extension attribute `{attr}`.");
        Ok(vec![quote! {
            impl #ty {
                #[doc = #doc]
                #[must_use]
                pub const fn #method(self) -> &'static str { #body }
            }
        }])
    }
}

Field pairs: pairs("exponent", "with_exponent") adds {field}_with_exponent for every fixed field whose mark names another fixed field, returning both accessors’ values with their exact types (Option, domain types and [u8; 16] arrays included). A target in an enclosing block (a group mantissa whose exponent sits on the message) makes the helper take that block’s decoder; a target found nowhere fails generation.

/// `attr` on a fixed field whose value names another fixed field ->
/// `{field}_{suffix}` returning both decoder accessors' values, exactly typed.
///
/// A target in the same block gives `fn x_{suffix}(&self) -> (A, B)`. A target
/// only in an enclosing block (a group field naming a message field) gives
/// `fn x_{suffix}(&self, outer: &Outer<'a>) -> (A, B)`, reading the target
/// from the nearest enclosing decoder that has it. A target found nowhere
/// fails generation.
pub fn pairs(
    attr: &'static str,
    suffix: &'static str,
) -> impl Fn(&ItemContext) -> Out + Send + Sync + 'static {
    move |ctx| {
        let (owner, fields, enclosing) = match ctx {
            ItemContext::MessageDecoder { name, fields, .. } => (name, fields, &[][..]),
            ItemContext::GroupEntryDecoder {
                name,
                fields,
                enclosing,
                ..
            } => (name, fields, enclosing.as_slice()),
            _ => return Ok(vec![]),
        };
        let mut methods = Vec::new();
        for f in fields {
            let Some(target) = f.extensions.attr(attr) else {
                continue;
            };
            let (fa, fty) = accessor(f)?;
            let helper = ident(&format!("{}_{suffix}", f.name))?;
            if let Some(t) = fields.iter().find(|t| t.schema_name == target) {
                let (ta, tty) = accessor(t)?;
                methods.push(quote! {
                    #[inline]
                    pub fn #helper(&self) -> (#fty, #tty) { (self.#fa(), self.#ta()) }
                });
                continue;
            }
            let Some((outer, t)) = enclosing.iter().rev().find_map(|b| {
                b.fields
                    .iter()
                    .find(|t| t.schema_name == target)
                    .map(|t| (b, t))
            }) else {
                return Err(format!(
                    "{owner}: `{}` {attr}=\"{target}\" names no field",
                    f.schema_name
                ));
            };
            let (ta, tty) = accessor(t)?;
            let outer = ident(&outer.decoder)?;
            methods.push(quote! {
                #[inline]
                pub fn #helper(&self, outer: &#outer<'a>) -> (#fty, #tty) {
                    (self.#fa(), outer.#ta())
                }
            });
        }
        if methods.is_empty() {
            return Ok(vec![]);
        }
        let owner = ident(owner)?;
        Ok(vec![quote! { impl<'a> #owner<'a> { #(#methods)* } }])
    }
}

Shared helpers:

/// One Rust identifier from user text, or an error.
pub fn ident(s: &str) -> Result<Ident, String> {
    let mut it = s
        .parse::<TokenStream>()
        .map_err(|e| format!("`{s}`: {e}"))?
        .into_iter();
    match (it.next(), it.next()) {
        (Some(TokenTree::Ident(i)), None) => Ok(i),
        _ => Err(format!("`{s}` is not one Rust identifier")),
    }
}

/// A fixed field's decoder accessor and its exact return type.
pub fn accessor(f: &FieldInfo) -> Result<(Ident, TokenStream), String> {
    match (f.kind(), &f.accessor, &f.accessor_type) {
        (FieldKind::Fixed, Some(name), Some(ty)) => {
            let ty = ty.parse().map_err(|e| format!("`{ty}`: {e}"))?;
            Ok((ident(name)?, ty))
        }
        _ => Err(format!(
            "`{}` must be a fixed field with a decoder accessor",
            f.schema_name
        )),
    }
}

Register them as try-hooks, so a bad mark fails the build with GenerateError::Hook naming the item:

let config = ergo_sbe::GenerationConfig::new("msgs")
    .with_try_hook(ext_recipes::labels("jsonValue", "json_value"))
    .with_try_hook(ext_recipes::pairs("exponent", "with_exponent"))
    .with_extension_consts(true);

ExtensionAttr conversions

ConversionSelector::extension_attr(local_name) selects message and group fields carrying a mark; extension_attr_value(local_name, value) also pins the value exactly:

#![allow(unused)]
fn main() {
use ergo_sbe::{ConversionSelector, GenerationConfig};

let config = GenerationConfig::new("msgs").with_domain_type(
    ConversionSelector::extension_attr_value("exponent", "priceExponent"),
    "my_app::PriceMantissa",
);
}

Precedence is FieldPath > SemanticType > ExtensionAttr > NamedType; two extension domain selectors tying on one field with different Rust types fail generation instead of falling back to registration order. Scope is message and group fields only: marks on <data>, <group> elements and type-level declarations reach hooks but not this selector. The Rust type always comes from build.rs, never from the schema. Details: with_conversion vs with_domain_type.

Worked example

The exchange example builds a working tool on a published venue schema through these generic parts only: a try-hook generates a write_json renderer from the schema’s jsonPath, exponent and jsonDefaultValue marks, and recorded real SBE responses render to JSON equal to the venue’s own JSON responses.

Recipes

Runnable code: sbe-feature-tour src/lib.rs.

Quick reference

Known vs unknown group count:

#![allow(unused)]
fn main() {
pub fn encode_sample_car(buf: &mut [u8]) -> Result<usize, sbe_rt::EncodeError> {
    let mut extras = OptionalExtras::default();
    extras.cruise_control(true).sports_pack(true);

    // Buffer pre-sized from EncodedLength; try_* still validates extent.
    let len = CarEncoder::try_wrap_and_apply_header(buf, 0)
        .unwrap()
        .fixed(&CarFixedFields {
            serial_number: 1234,
            model_year: 2013,
            available: true.into(),
            code: Model::A,
            some_numbers: [10, 20, 30, 40],
            vehicle_code: [b'A', b'B', b'C', b'D', b'E', b'F'],
            extras,
            engine: Engine::new(
                2000,
                4,
                [b'1', b'2', b'3'],
                0i8,
                false.into(),
                Booster::new(BoostType::TURBO, 210),
            ),
        })
        .fuel_figures(2, |g| {
            g.add(|mut e| {
                e.speed(30).mpg(35.9);
                e.usage_description_as_str("Urban")
            })?;
            g.add(|mut e| {
                e.speed(60).mpg(25.0);
                e.usage_description_as_str("Highway")
            })?;
            Ok(())
        })?
        .performance_figures(1, |g| {
            g.add(|mut e| {
                e.octane_rating(95);
                e.acceleration(2, |a| {
                    a.add(|x| {
                        x.mph(30).seconds(4.0);
                        Ok(())
                    })?;
                    a.add(|x| {
                        x.mph(60).seconds(7.5);
                        Ok(())
                    })
                })
            })?;
            Ok(())
        })?
        .manufacturer_as_str("Honda")?
        .model_as_str("Civic VTi")?
        .activation_code_as_str("abcdef")?
        .encoded_length_with_header();

    Ok(len)
}
}

(From sbe-feature-tour: known-count groups with chaining, tested in CI.)

Unknown size: count back-patched after the closure (streaming producers).

let unknown_len = CarEncoder::wrap_and_apply_header(&mut buf, 0)
    .fixed(&fields)
    .fuel_figures_unknown_size(|g| {
        for row in rows {
            g.add(|mut e| {
                e.speed(row.speed).mpg(row.mpg);
                e.usage_description_as_str(&row.usage)
            })?;
        }
        Ok(())
    })?
    .performance_figures(0, |_| Ok(()))?
    .manufacturer_as_str("Honda")?
    .model_as_str("Civic")?
    .activation_code_as_str("active")?
    .encoded_length_with_header();

println!("known={known_len} unknown={unknown_len}");

Unknown enum values

A wire discriminant the schema never declared reaches you three different ways. Pick by what should happen:

What you wantUseBehaviour
Keep decoding; unknown means “not set”Typed getter, e.g. dec.code()from_raw folds every undeclared discriminant into NullVal; the decode continues
See the byte that arriveddec.raw_code()The raw discriminant unchanged (u8, …); schema null and unknown stay distinguishable (named *_wire when a conversion owns the plain name)
Refuse the frameGenerationConfig::with_validate(true), then dec.validate()?ValidateError::UnknownEnum { field, discriminant }
let code = dec.code();   // unknown → EventCode::NullVal; decode continues
dec.raw_code()           // 42u8 — the wire byte, unfolded
dec.validate()?          // with_validate(true): Err(UnknownEnum { discriminant: 42 })

The fold is lossy only in the typed view: a match on dec.code() cannot tell the schema’s null from an unknown value — compare raw_* for that, or make the unknown a hard error with validate(). validate() is opt-in and walks every field and group entry, so keep it off the hot path (Value validation); the fold itself is explained in Why NullVal instead of Option.

Aeron try_claim integration

ergo-sbe’s exact sizing is built for encoding straight into a claimed region: size the frame, claim exactly that many bytes, encode into the claim, commit. No scratch buffer, no copy. Connecting and adding the publication: rusteron-client. The generated send and send_fixed do the last three steps and check the result, so a frame that does not fill its claim is a typed error and the claim is aborted, never a corrupt publication.

Animation, in words: the Note from the examples below, body "rebalance at close", is 34 bytes (header 8, noteId 4, length prefix 4, body 18), and compute_length_with_header(18) gives that before any buffer exists. try_claim_owned(34) moves the log’s tail on by 96 bytes (Aeron’s 32-byte header plus 34, rounded up to 32) and writes the header with a negative length, −66, so subscribers stop in front of the frame. send wraps the encoder on the claimed bytes and writes the header, noteId, length and body in place; send_frame checks 34 against 34 and the header template, then commit stores +66 and subscribers read past the frame. A 35-byte claim fails with LengthMismatch, and a 19-byte body in a claim sized for 18 fails with BufferTooShort after only the header and noteId are written (the setter checks room before it writes); either way the claim is aborted, Aeron turns the frame into padding, and subscribers skip it. The offer route zeroes a 34-byte scratch buffer, encodes into it, and offer copies the 34 bytes into the log: three writes of the frame against one. AeronCluster::try_claim(34) claims 32 + 34 bytes and writes the 32-byte SessionMessageHeader first; the Note goes into payload_mut(). try_claim needs the exact length first, fits one frame only, and stalls subscribers while a claim is open. These are byte counts from the code, not timings.

The Claim trait

Every generated module’s sbe_rt declares Claim, a region a transport reserved for one frame. ergo-sbe has no Aeron dependency, so you implement it once for your transport. In the crate that generates the codec the trait is local, so rusteron’s claim type can implement it directly (from another crate, where both are foreign, wrap the claim in a newtype):

use rusteron_client::{AeronCError, AeronClaim};

impl messages::sbe_rt::Claim for AeronClaim<'_> {
    type Error = AeronCError;
    fn frame_mut(&mut self) -> &mut [u8] {
        self.data()
    }
    fn commit(self) -> Result<(), AeronCError> {
        AeronClaim::commit(self).map(drop)
    }
    fn abort(self) {
        let _ = AeronClaim::abort(self);
    }
}

send calls abort whenever it publishes nothing (an encoder error, a length or header mismatch, or unwinding from a panic in your closure), so the term-buffer slot is released at once rather than after Aeron’s unblock timeout.

No encoder writes a block’s padding (the bytes past its last field, up to the schema’s blockLength), so they go out as the claimed region held them. An Aeron try_claim region starts zeroed by the transport; the cost of that zeroing is not measured here. A Claim you implement over a region the transport reuses must hand it out zeroed, as OfferClaim (below) does.

Fixed-only messages: send_fixed

let claim = publication.try_claim_owned(HeartbeatEncoder::ENCODED_LENGTH)?;
HeartbeatEncoder::send_fixed(claim, &HeartbeatFixedFields { sequence: 7, timestamp: 0 })?;

A claim of any other size is SendError::LengthMismatch, and nothing is written into it.

Messages with groups and var-data: send

Size the frame with the encoder’s compute_length* helpers (or the staged EncodedLength builder for nested groups), claim that length, and hand send a closure that writes the message. The closure receives the encoder already wrapped on the claim, header written, and must return the message’s terminal stage, so a frame with tails still to write does not compile:

let len = NoteEncoder::compute_length_with_header(body.len());
NoteEncoder::send(publication.try_claim_owned(len)?, |enc| {
    enc.fixed(&NoteFixedFields { note_id: 1 }).body(body)
})?;

send checks that the frame is exactly the claim’s length (a claim sized for a different frame would otherwise publish stale bytes or a truncated message) and that it starts with the message’s own header. Each failure has its own SendError variant: Encode for the encoder’s error, LengthMismatch, HeaderMismatch, and Commit for the transport refusing the frame, the only case where the claim was not aborted, because the transport already had it.

Offer-style transports: OfferClaim

A transport that copies a finished frame, like Aeron’s offer, uses sbe_rt::OfferClaim over a scratch buffer: the frame is encoded into the buffer, and committing hands it to the closure. The same send and send_fixed work unchanged, with the same checks. OfferClaim::new zeroes the buffer, so a scratch buffer reused for every frame never puts the previous frame’s bytes in the next one’s padding:

#![allow(unused)]
fn main() {
// Offer style: encode into `scratch`; commit hands the frame to the transport.
let mut scratch = [0u8; HeartbeatEncoder::ENCODED_LENGTH];
let mut published: Vec<Vec<u8>> = Vec::new();
let claim = sbe_rt::OfferClaim::new(&mut scratch, |frame: &[u8]| -> Result<(), &'static str> {
    published.push(frame.to_vec()); // publication.offer(frame).map(drop)
    Ok(())
});
HeartbeatEncoder::send_fixed(claim, &HeartbeatFixedFields { sequence: 7, timestamp: 0 })?;
assert_eq!(published.len(), 1);
}
#![allow(unused)]
fn main() {
let body = b"rebalance at close";
let len = NoteEncoder::compute_length_with_header(body.len());
let mut scratch = vec![0u8; len];
let claim = sbe_rt::OfferClaim::new(&mut scratch, |frame: &[u8]| -> Result<(), &'static str> {
    assert_eq!(frame.len(), len);
    Ok(())
});
// The closure gets the encoder wrapped on the claim and must return the
// finished frame: the type-state makes a half-written one a compile error.
NoteEncoder::send(claim, |enc| enc.fixed(&NoteFixedFields { note_id: 1 }).body(body))?;
}
#![allow(unused)]
fn main() {
// A claim one byte too long: nothing is offered, and the error says why.
let body = b"rebalance at close";
let len = NoteEncoder::compute_length_with_header(body.len());
let mut too_long = vec![0u8; len + 1];
let claim = sbe_rt::OfferClaim::new(&mut too_long, |_: &[u8]| -> Result<(), &'static str> {
    unreachable!("an aborted claim is never offered")
});
let sent = NoteEncoder::send(claim, |enc| enc.fixed(&NoteFixedFields { note_id: 1 }).body(body));
assert_eq!(
    sent,
    Err(sbe_rt::SendError::LengthMismatch { claimed: len + 1, frame: len })
);
}

(From book/examples/claim-send.rs, compiled against the feature-tour codec.)

Encoding an application type

With with_source_traits, the encoder can write any type that implements the message’s generated …Source trait, sizing it first with encoded_length_with_header_from. encode_from returns the terminal stage, so it is the whole send closure:

#![allow(unused)]
fn main() {
/// The application's own type: no generated struct is involved.
struct Reminder {
    id: u32,
    text: String,
}

impl NoteSource for Reminder {
    fn note_id(&self) -> u32 {
        self.id
    }
    fn body(&self) -> &[u8] {
        self.text.as_bytes()
    }
}

let reminder = Reminder { id: 9, text: "settle T+1".into() };
let len = NoteEncoder::encoded_length_with_header_from(&reminder)?;
let mut scratch = vec![0u8; len];
let claim = sbe_rt::OfferClaim::new(&mut scratch, |_: &[u8]| -> Result<(), &'static str> { Ok(()) });
NoteEncoder::send(claim, |enc| enc.encode_from(&reminder))?;
}

encode_from refuses what would not read back: Some of an optional field’s null value (NaN for a float) is EncodeError::SomeNullValue, and a value a domain conversion refuses is EncodeError::Conversion, each with the field’s path and entry indices (fills[1].allocs[0].px). An integer or char scalar outside a minValue / maxValue the schema declares is EncodeError::ValueOutOfRange; a bound the schema does not declare is not checked, so u64::MAX in a plain uint64 is written as given. In a hand-written closure, the setter of a field under with_enum_mapping or with_composite_mapping returns sbe_rt::MappingError, which converts into EncodeError, so enc.side(side)? works there too.

A frame written some other way: send_frame

sbe_rt::send_frame(claim, header, encode) is what send is built on: it runs a closure that writes raw bytes into the claim and returns the frame’s length, then applies the same length and header checks before committing. Pass the message’s HEADER_TEMPLATE as header. Use it when the frame is not written through one generated encoder, for example a bus that encodes whichever message a caller hands it, and for a message whose own field, or first group or var-data, is named send (or send_fixed): that accessor is a method on the encoder too, so it keeps its name and the message has no helper of that name.

Cluster clients

Cluster clients do not claim from the publication directly: use AeronCluster::try_claim, which claims SessionMessageHeader + payload and hands back the payload region via ClusterClaim::payload_mut().

The cluster-ha-orderbook sample demonstrates the claim pattern in the context of a real Aeron Cluster publication loop.

Display / Debug

Diagnostic only; not a stable wire or log schema. Do not treat either format as a protocol or long-term log contract.

Display currently equals Debug for generated decoders ({car} and {car:?} print the same text). Prefer Debug in logs if you want that intent to stay obvious when/if the two diverge later.

#![allow(unused)]
fn main() {
pub fn demo_display_debug(valid_car: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let car = CarDecoder::try_from(valid_car)?;
    let display = format!("{car}");
    let debug = format!("{car:#?}");

    // Display is a compact one-liner; field names use the schema's camelCase.
    assert!(display.contains("serialNumber: 1234"));
    assert!(display.contains("modelYear: 2013"));
    assert!(display.contains("available: true"));
    assert!(display.contains(r#"code: A"#));
    assert!(display.contains("manufacturer: \"Honda\""));
    assert!(display.contains("model: \"Civic VTi\""));
    assert!(display.contains("fuelFigures: ["));
    assert!(display.contains("performanceFigures: ["));
    assert!(display.contains(r#"activationCode: "abcdef""#));

    // Pretty Debug ({:#?}) shows each field on its own line with indentation.
    for expected in &[
        "serialNumber: 1234",
        "modelYear: 2013",
        "available: true",
        r#"manufacturer: "Honda""#,
        r#"model: "Civic VTi""#,
        r#"activationCode: "abcdef""#,
        r#"usageDescription: "Urban""#,
        "speed: 30",
        "mpg: 35.9",
        "octaneRating: 95",
    ] {
        assert!(
            debug.contains(expected),
            "Debug missing: {expected}\n--- full debug ---\n{debug}"
        );
    }

    // ── CarDomain DTO ───────────────────────────────────────────────────
    // Owned, heap-allocated, serialisable snapshot of the full message tree.
    // Generated by `with_domain_objects(DomainVarData::Strings)`.
    let dto = CarDomain::try_from_decoder(car)?;
    let dto_dbg = format!("{dto:#?}");
    // DTO field names use Rust snake_case (different from wire decoder camelCase).
    assert!(dto_dbg.contains("serial_number: 1234"));
    assert!(dto_dbg.contains("model_year: 2013"));
    assert!(dto_dbg.contains("available: true"));
    assert!(dto_dbg.contains("fuel_figures: ["));
    assert!(dto_dbg.contains(r#"usage_description: "Urban""#));
    assert!(dto_dbg.contains(r#"manufacturer: "Honda""#));
    assert!(dto_dbg.contains(r#"activation_code: "abcdef""#));

    Ok(())
}
}

(This code comes from the sbe-feature-tour sample crate.)

Real output from the feature-tour Car (the CarDecoder that demo_car_size_and_encode produces):

CarDecoder { serialNumber: 1234, modelYear: 2013, available: true, code: A, extras: sportsPack|cruiseControl, engine: Engine { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: [49, 50, 51], fuel: "Petrol", efficiency: 0, boosterEnabled: F, booster: Booster { BoostType: TURBO, horsePower: 210 } }, fuelFigures: [CarFuelFiguresEntryDecoder { speed: 30, mpg: 35.9, usageDescription: "Urban" }, CarFuelFiguresEntryDecoder { speed: 60, mpg: 25.0, usageDescription: "Highway" }], performanceFigures: [CarPerformanceFiguresEntryDecoder { octaneRating: 95, acceleration: [CarPerformanceFiguresAccelerationEntryDecoder { mph: 30, seconds: 4.0 }, CarPerformanceFiguresAccelerationEntryDecoder { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi", activationCode: "abcdef" }

Group entries print as nested structures, in wire order (fields, nested groups, var data), and {:#?} indents them. An entry that fails to decode shows as its DecodeError.

Truncated / incomplete buffers omit missing tails rather than panicking.

No compiled codec for the bytes? ergo-sbe-inspect reads them at run time from the schema file and prints the same field names and leaf values, plus the fields Display skips; containers differ on purpose (Inspect bytes with no codec).

Schema descriptions as rustdoc

<field name="serialNumber" id="1" type="uint64" description="VIN-style serial"/>
// Generated (approx):
/// VIN-style serial
pub fn serial_number(&self) -> u64 { … }

Provenance of all four XML doc sources: schema_docs_provenance_test.

Domain DTOs

This is the encode and decode recipe for an owned DTO. When to prefer a flyweight: Flyweight vs whole struct. with_conversion versus with_domain_type (a Rust type on the flyweight, not an owned DTO): with_conversion vs with_domain_type. The compiled tour example is Domain objects.

Use a DTO when you want owned values (Vec groups, owned tails) and simple structs, not the zero-copy hot path. DTOs allocate on decode; the flyweight path does not. A DTO-vs-flyweight latency A/B was not measured.

For re-encode, eligible flat groups are bulk-written directly from &[EntryDomain]: no temporary Vec<Entry> and no encode-time allocation. Eligibility requires fixed-size entries whose domain fields have the same wire representation; nested groups, var-data, optional/versioned fields, configured domain conversions, and bool remapping use the general add path. Both paths check integer and char scalars written as their wire type against the minValue / maxValue the schema declares, and only those (EncodeError::ValueOutOfRange). A side the schema does not declare is not checked, so a required uint32 of u32::MAX is written as given. Composite members and array elements are not checked. fixed() and the plain setters check no range. with_all_enums_as_option() / with_null_as_option maps a required enum to Option<Enum> on the DTO: None writes the schema NullVal image (including on a reused buffer), and bulk_add_domain / to_wire_entry use that same mapping.

DTO re-encode of eligible flat groups is a DTO-to-DTO diagnostic (group_encode_bench), not an ergon/sbe-tool ratio. Read a fresh run; do not quote numbers from this page.

#![allow(unused)]
fn main() {
// build.rs: DomainVarData picks the DTO field type for var-data:
// .with_domain_objects(DomainVarData::Strings) // String (invalid UTF-8 → InvalidUtf8 error)
// .with_domain_objects(DomainVarData::Bytes)        // Vec<u8> (byte-exact)
}

Generated shape (illustrative; your names follow your schema):

pub struct QuoteDomain {
    pub seq: u32,
    pub some_numbers: [u32; 4],
    pub vehicle_code: [u8; 6],
    pub qty: u32,
    pub legs: Vec<QuoteLegsEntryDomain>,
    pub note: Vec<u8>,              // Bytes|String per DomainVarData
}
impl QuoteDomain {
    // Named methods, not TryFrom/From: two fallible sources (decoder vs framed
    // slice+offset), and materialisation is never infallible.
    pub fn try_from_decoder(dec: QuoteDecoder<'_>) -> Result<Self, DecodeError>;
    pub fn try_from_slice_with_header(buf: &[u8], offset: usize) -> Result<Self, DecodeError>;
    pub fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError>;
    pub fn encoded_length_with_header(&self) -> Result<usize, EncodeError>;
}

Wire to DTO and back (the docs fixture uses DomainVarData::Bytes):

#![allow(unused)]
fn main() {
  // Encode a message first (the usual flyweight path)
  let mut buf = [0u8; QuoteEncoder::compute_length_with_header(1, 2)];
  let len = QuoteEncoder::wrap_and_apply_header(&mut buf, 0)
      .fixed(&QuoteFixedFields {
          seq: 1,
          some_numbers: [1, 2, 3, 4],
          vehicle_code: *b"ABCDEF",
          qty: 10,
      })
      .legs(1, |legs| {
          legs.add(|leg| { leg.value(99); Ok(()) })?;
          Ok(())
      })?
      .note_as_str("hi")?
      .encoded_length_with_header();
  // Decode to an owned DTO (allocates, so not for the hot path)
  let dec = QuoteDecoder::try_from(&buf[..len])?;
  let mut dto = QuoteDomain::try_from_decoder(dec)?;
  assert_eq!(dto.seq, 1);
  assert_eq!(&dto.note, b"hi");
  dto.qty = 500;
  // Re-encode (integer min/max checked; eligible groups use bulk write)
  let n = dto.encode(&mut buf)?;
  assert_eq!(n, len);
}

with_domain_objects(DomainVarData)

SBE <data> is length-prefixed bytes. The enum picks the DTO field type:

CallField typeInvalid UTF-8When to use
.with_domain_objects(DomainVarData::Strings)StringInvalidUtf8 error (strict)Text schemas when validity is known
.with_domain_objects(DomainVarData::Bytes)Vec<u8>n/a (raw copy)Binary tails or byte-exact re-encode

Strings rejects invalid UTF-8. Materialise returns InvalidUtf8 for bad bytes; there is no silent empty-string fallback. Use Bytes (or stay on flyweights) when you need audit / replay fidelity of non-UTF-8 tails.

Runnable demo (text path): sbe-feature-tour uses DomainVarData::Strings. Flyweight path is unchanged: with schema characterEncoding="UTF-8" you still get into_manufacturer_as_str() without a DTO.

demo_car_domain_dto · domain_objects_test.

App types on composites

SBE composite types like Decimal { mantissa, exponent } have a fixed wire layout. Mapping them to Rust domain types is done at configuration time, with no hand-rolled per-field converters.

Option A, generic converter (with_conversion): the generated codec emits price_from<T: TryToSbe<Decimal>>() and price_as<T: TryFromSbe<Decimal>>(). You implement the trait for any app type. One wire type, many app types.

Option B, concrete mapping (with_domain_type): the generated codec emits price(rust_decimal::Decimal)? and price()? -> rust_decimal::Decimal. Exactly one Rust type per wire type. The trait impls are generated for you.

Option C, generated mapping (with_enum_mapping, with_composite_mapping): for an enum or composite whose application counterpart has the same shape, ergo-sbe writes the TryFromSbe / TryToSbe impls too. See below.

Full comparison with code examples: with_conversion vs with_domain_type.

Generated mappings

An application enum that mirrors an SBE enum, and a struct that mirrors a composite, need no hand-written conversion:

    GenerationConfig::new(module)
        .with_enum_mapping(
            EnumMapping::new("Side", "app::Side")
                .rename("Buy", "Bid")
                .rename("Sell", "Ask"),
        )
        .with_composite_mapping(CompositeMapping::new("Price", "app::Px"))
        .with_composite_mapping(CompositeMapping::new("Leg", "app::Leg").rename("qty", "quantity"))
pub mod app {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Side { Bid, Ask, SellShort }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Px { pub mantissa: i64, pub exponent: i8 }

    #[derive(Debug, Clone, Copy, PartialEq)]
    pub struct Leg {
        pub price: Px,
        pub side: Side,
        pub quantity: u32,
        pub min_qty: Option<u32>,
        pub ratio: Option<f64>,
        pub flags: super::Flags,
        pub venue: [u8; 4],
    }
}

(From sbe/tests/type_mapping_test.rs, which generates, compiles and runs these against the plain codec.)

Each mapping also acts as a with_domain_type for its type, so every field of that type takes the application type: dec.side()? -> app::Side, enc.leg(leg)?, and the application type in a domain DTO (a DTO field of an enum named BooleanType, or with semanticType="Boolean", stays bool, as under with_domain_type). A presence="constant" field of a mapped enum has the same domain getter beside its *_wire getter, and no setter. The wire bytes are the ones the plain codec writes.

A mapped setter’s error is sbe_rt::MappingError, which converts into sbe_rt::EncodeError, so enc.leg(leg)? works inside an encode or send closure. A domain DTO’s encode and encode_from report the same refusal as EncodeError::Conversion, with the field’s path and the index of its entry in each group on the way (fills[1].leg) and the MappingError itself.

Enum (EnumMapping). A schema variant maps to the application variant of the same generated name (sellShort maps to SellShort) unless renamed. Both impls are exhaustive matches, so an application enum that lacks a schema variant, or has one the schema lacks, does not compile.

Composite (CompositeMapping). TryFromSbe is a struct literal built from the composite’s getters, TryToSbe calls the composite’s new; a member fills the field of the same snake-case name unless renamed. Constant members have no field (they are not on the wire). An optional scalar member is an Option field: None writes the member’s null value, and Some of the null value, which would read back as None, is refused. A member whose enum or composite has its own generated mapping uses that mapping’s application type (price: app::Px, side: app::Side above); every other member keeps its generated wire type. A struct missing a member’s field, or with a field no member fills, does not compile.

NullVal and unknown values

NullVal has no application value, so decoding it is an explicit sbe_rt::MappingError::NullEnum, never a default variant. The generated decoder folds every discriminant the schema does not declare into NullVal before the mapping sees it, so an unknown value is the same error: the mapping cannot tell it from the schema null, and only the decoder’s raw_<field>() still reads the wire byte. With with_null_as_option on the enum, both read as Ok(None) instead:

        let side_at = dm::OrderEncoder::HEADER_LENGTH + 8;
        assert_eq!(buf[side_at], 5, "sellShort's discriminant");
        for raw in [0u8, 9] {
            // 0 is NullVal; 9 is undeclared and folds into NullVal on decode.
            buf[side_at] = raw;
            let dec = dm::OrderDecoder::decode(&buf, 0)?;
            assert_eq!(dec.side_wire(), dm::Side::NullVal);
            assert_eq!(dec.side(), Err(dm::sbe_rt::MappingError::NullEnum { enum_name: "Side" }));
            assert!(dm::OrderDomain::try_from_slice_with_header(&buf[..len], 0).is_err());

            // with_null_as_option: absent instead of an error — for the
            // undeclared 9 too, the folding limitation.
            let dec = dmo::OrderDecoder::decode(&buf, 0)?;
            assert_eq!(dec.side(), Ok(None));
        }
        buf[side_at] = 2;
        assert_eq!(dmo::OrderDecoder::decode(&buf, 0)?.side(), Ok(Some(dmo::app::Side::Ask)));

On a presence="optional" field, NullVal is not an error but the field being absent, so a mapped enum that such a field uses needs with_null_as_option: without it, generation fails with GenerateError::InvalidConfiguration naming the field, instead of every valid frame that leaves the field out failing to decode.

Optional composites with a null image

A composite member itself can carry presence="optional" with a schema nullValue (for example a PriceNull9-style Decimal whose mantissa is optional while exponent stays constant). That member decodes as Option<i64> (checked against the wire null sentinel), not a bare i64. This is distinct from a composite field gated by sinceVersion (which the whole composite accessor wraps in Option<Decoder>), and from a composite with no nullValue anywhere (which has no null image to check, so it decodes as a plain value; see with_conversion vs with_domain_type).

Because the wire null sentinel is not a valid rust_decimal::Decimal, the with_domain_type accessor fails closed with a typed error rather than silently decoding the sentinel as a huge/wrong number:

        use rust_decimal::Decimal;

        // `price: None` writes the schema null image (mantissa = nullValue).
        let mut buf = [0u8; QuoteEncoder::compute_length_with_header()];
        let len = QuoteEncoder::wrap_and_apply_header(&mut buf, 0)
            .fixed(&QuoteFixedFields { price: None, qty: 7 })
            .encoded_length_with_header();

        let dec = QuoteDecoder::try_decode(&buf[..len], 0)?;
        assert_eq!(dec.price_value().mantissa(), None);
        assert!(dec.price().is_err(), "null mantissa is not a valid Decimal");

        // A real price round-trips through the null-aware member accessor.
        let len2 = QuoteEncoder::wrap_and_apply_header(&mut buf, 0)
            .fixed(&QuoteFixedFields { price: None, qty: 7 })
            .price(Decimal::new(12345, 9))?
            .encoded_length_with_header();
        let dec2 = QuoteDecoder::try_decode(&buf[..len2], 0)?;
        assert_eq!(dec2.price_value().mantissa(), Some(12345));
        assert_eq!(dec2.price()?, Decimal::new(12345, 9));

(From optional_composite_member_null_image_roundtrip in sbe/tests/baseline_test.rs, a real generated-and-compiled test, not a standalone snippet.)

Timestamp conversions

SBE timestamps are typically uint64 fields with a semanticType (UTCTimestamp = nanos, UTCTimestampMicros = micros, UTCTimestampMillis = millis). The chrono feature maps them to DateTime<Utc> / NaiveDateTime. Enable it on both Cargo entries:

[build-dependencies]
ergo-sbe = { version = "0.1", features = ["chrono"] }

[dependencies]
ergo-sbe = { version = "0.1", features = ["chrono"] }
chrono = "0.4"

Then register the converters by semanticType in build.rs:

use ergo_sbe::{ConversionSelector, GenerationConfig};

let config = GenerationConfig::new("msgs")
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestamp"),
        "chrono::DateTime<chrono::Utc>",
    )
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestampMicros"),
        "chrono::NaiveDateTime",
    );

Schema:

<field name="created_at"  id="1" type="uint64" semanticType="UTCTimestamp"/>
<field name="updated_at"  id="2" type="uint64" semanticType="UTCTimestampMicros"/>

In the generated API, created_at() returns DateTime<Utc> and updated_at() returns NaiveDateTime (not built in: you write its TryFromSbe<u64> and TryToSbe<u64> impls):

// Decode
let created: chrono::DateTime<chrono::Utc> = dec.created_at()?;
let updated: chrono::NaiveDateTime = dec.updated_at()?;

// Encode
enc.created_at(chrono::Utc::now())?;
enc.updated_at(
    chrono::DateTime::from_timestamp_micros(1_720_000_000_000_000)
        .ok_or("micros out of range")?
        .naive_utc(),
)?;

timeUnit on a UTCTimestamp field

A uint64 UTCTimestamp field may say what it counts with timeUnit (second, millisecond, microsecond or nanosecond; nanoseconds when absent). The built-in DateTime<Utc> conversion honours it: the domain accessors read and write the field in its own unit, so one semantic_type("UTCTimestamp") mapping serves fields of every precision.

<field name="sentAt" id="1" type="uint64" semanticType="UTCTimestamp" timeUnit="millisecond"/>

Writing a DateTime more precise than the field (sub-millisecond digits into a millisecond field) is an error rather than a truncation; truncate it first (chrono::DurationRound::duration_trunc) when that is what you mean. Under DomainImpl::Manual your impl receives the field’s own unit.

One selector, many fields

ConversionSelector::semantic_type(..) matches every field in the schema carrying that semanticType, not just one. You register the conversion once, not once per field. A schema with three separate UTCTimestamp timestamps needs no more config than one with a single field:

<field name="createdAt"  id="1" type="uint64" semanticType="UTCTimestamp"/>
<field name="updatedAt"  id="2" type="uint64" semanticType="UTCTimestamp"/>
<field name="expiresAt"  id="3" type="uint64" semanticType="UTCTimestamp"/>
// Same one-time call as the two-field example above, no per-field repeats.
let config = GenerationConfig::new("msgs")
    .with_domain_type(
        ConversionSelector::semantic_type("UTCTimestamp"),
        "chrono::DateTime<chrono::Utc>",
    );

All three fields get their own concrete accessor, generated from that one call:

enc.created_at(chrono::Utc::now())?;
enc.updated_at(chrono::Utc::now())?;
enc.expires_at(chrono::Utc::now())?;

let created: chrono::DateTime<chrono::Utc> = dec.created_at()?;
let updated: chrono::DateTime<chrono::Utc> = dec.updated_at()?;
let expires: chrono::DateTime<chrono::Utc> = dec.expires_at()?;

This is why UTCTimestamp and UTCTimestampMicros need separate with_domain_type calls in the two-field example above (they are different semanticType strings, so they are different selectors), but adding a fourth UTCTimestamp field to the same schema needs no config change at all. ConversionSelector::field_path is the escape hatch when one specific field needs to differ from its semantic-type siblings. It works because selectors resolve by precedence, not registration order: an exact FieldPath beats a SemanticType, which beats a NamedType. So a blanket semantic_type("UTCTimestamp") mapping plus one field_path("Order.settledAt") override does what it reads like, regardless of which you register first.

Paths are "Message.field", extended with the group names for fields inside a group: "Order.legs.settledAt".

A schema that names its timestamps with an alias instead of a semanticType (<type name="Timestamp" primitiveType="uint64"/>) is selected the same way through ConversionSelector::named_type("Timestamp"): every field declared type="Timestamp" gets the domain accessors, and the raw *_wire accessor stays.

Mixed precisions, one app type: DomainImpl::Manual

The only built-in timestamp conversion makes DateTime<Utc> for a uint64 UTCTimestamp field; any other type, NaiveDateTime included, needs your own impls. The example above ends in two app types. The opposite is common: three fields at three different wire precisions, all normalised to the same DateTime<Utc> so downstream app code never branches on precision. None of the three is the bare uint64 + semanticType="UTCTimestamp" shape the built-in converter matches, so none gets an auto-generated impl. That is exactly the case DomainImpl::Manual is for: concrete domain accessor signatures from ergo-sbe, conversion body from you.

Distinguish the three precisions with single-element composites (a distinct Rust type per precision: TimestampMillis(u64) is not TimestampNanos(u64) even though the wire shape is identical):

<composite name="TimestampMillis"><type name="ts" primitiveType="uint64"/></composite>
<composite name="TimestampMicros"><type name="ts" primitiveType="uint64"/></composite>
<composite name="TimestampNanos"><type name="ts" primitiveType="uint64"/></composite>

<field name="createdAt" id="1" type="TimestampNanos"/>
<field name="updatedAt" id="2" type="TimestampMicros"/>
<field name="deletedAt" id="3" type="TimestampMillis"/>

One with_manual_domain_type(selector, path) call per composite, all with the same target type, goes in build.rs:

use ergo_sbe::{ConversionSelector, GenerationConfig};

let config = GenerationConfig::new("msgs")
    .with_manual_domain_type(
        ConversionSelector::named_type("TimestampNanos"),
        "chrono::DateTime<chrono::Utc>",
    )
    .with_manual_domain_type(
        ConversionSelector::named_type("TimestampMicros"),
        "chrono::DateTime<chrono::Utc>",
    )
    .with_manual_domain_type(
        ConversionSelector::named_type("TimestampMillis"),
        "chrono::DateTime<chrono::Utc>",
    );

Each composite is a genuinely new named type, so there is no built-in template to offer, so write the three impls yourself, one per precision (the traits live at the root of the generated module as TryFromSbe / TryToSbe; import from there, not from ergo_sbe::codegen, which is crate-private):

// my_msgs is the module name passed to GenerationConfig::new("my_msgs")
use my_msgs::{TryFromSbe, TryToSbe};
use my_msgs::{TimestampMillis, TimestampMicros, TimestampNanos};

impl TryFromSbe<TimestampNanos> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_from_sbe(wire: TimestampNanos) -> Result<Self, Self::Error> {
        // A single-member composite wraps its wire bytes: TimestampNanos([u8; 8]).
        let ns = u64::from_le_bytes(wire.0);
        chrono::DateTime::from_timestamp((ns / 1_000_000_000) as i64, (ns % 1_000_000_000) as u32)
            .ok_or("timestamp out of range")
    }
}
impl TryToSbe<TimestampNanos> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_to_sbe(&self) -> Result<TimestampNanos, Self::Error> {
        // The wire type is uint64: pre-epoch has no representation, so it is
        // an error. `as u64` on a negative i64 would wrap silently.
        let ns = self.timestamp_nanos_opt().ok_or("overflow")?;
        let ns = u64::try_from(ns).map_err(|_| "timestamp before 1970")?;
        Ok(TimestampNanos(ns.to_le_bytes()))
    }
}

impl TryFromSbe<TimestampMicros> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_from_sbe(wire: TimestampMicros) -> Result<Self, Self::Error> {
        let us = u64::from_le_bytes(wire.0);
        chrono::DateTime::from_timestamp((us / 1_000_000) as i64, ((us % 1_000_000) * 1_000) as u32)
            .ok_or("timestamp out of range")
    }
}
impl TryToSbe<TimestampMicros> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_to_sbe(&self) -> Result<TimestampMicros, Self::Error> {
        let us = u64::try_from(self.timestamp_micros()).map_err(|_| "timestamp before 1970")?;
        Ok(TimestampMicros(us.to_le_bytes()))
    }
}

impl TryFromSbe<TimestampMillis> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_from_sbe(wire: TimestampMillis) -> Result<Self, Self::Error> {
        let ms = u64::from_le_bytes(wire.0);
        chrono::DateTime::from_timestamp((ms / 1000) as i64, ((ms % 1000) * 1_000_000) as u32)
            .ok_or("timestamp out of range")
    }
}
impl TryToSbe<TimestampMillis> for chrono::DateTime<chrono::Utc> {
    type Error = &'static str;
    fn try_to_sbe(&self) -> Result<TimestampMillis, Self::Error> {
        let ms = u64::try_from(self.timestamp_millis()).map_err(|_| "timestamp before 1970")?;
        Ok(TimestampMillis(ms.to_le_bytes()))
    }
}

All three fields now return the exact same app type despite three different wire precisions, so the caller never needs to know which precision a given field was wire-encoded at:

let created: chrono::DateTime<chrono::Utc> = dec.created_at()?;
let updated: chrono::DateTime<chrono::Utc> = dec.updated_at()?;
let deleted: chrono::DateTime<chrono::Utc> = dec.deleted_at()?;

enc.created_at(chrono::Utc::now())?;
enc.updated_at(chrono::Utc::now())?;
enc.deleted_at(chrono::Utc::now())?;

If you forget one of the three impls, the compile error names it directly (`chrono::DateTime<Utc>` has no `TryFromSbe<TimestampMillis>` impl) instead of the default trait-bound message.

Design notes

Type-state and runtime cost

Stage identity adds no runtime tag. The named structs carry buffer and cursor state; markers such as HeaderPresent are zero-sized. A transition moves that state into the next concrete type:

(buf, msg_offset, offset)  +  PhantomData / zero-sized stage identity

No heap, no vtable, no enum discriminant, no “which stage am I in?” branch: the stage is the type, so the methods that exist are the ones legal at that point. Inlining can remove the intermediate moves. Decoder stages also carry acting version and block length; dynamic group callbacks check that the returned completion belongs to the supplied entry.

The sbe-tool gate compares two different codecs, so it cannot isolate the cost of type-state, and no benchmark here measures that cost on its own. A measurable type-state tax would be a codegen defect. Gate and method: Benchmarks.

Named stages (CarEncoder, CarAfterFuelFigures, CarComplete) are the type-state pattern. The other spelling is Encoder<'a, Stage> with phantom markers. This crate uses named stages; the two were not compared.

ConcernChoiceWhy
Linear tail (groups / var-data)Named structs per stageA wrong-order call is E0599 naming the stage you hold; each stage’s rustdoc lists the one call that moves on
Header vs body-onlyOne H: HeaderState on every stageAvoids doubling the graph. Default H = HeaderPresent
Completeness of the fixed blockF: FieldsState on the root encoderas_bytes_with_header exists only after fixed(&FixedFields)

Tail stages drop F: they are already past the fixed block.

pub struct BookEncoder<'a, H: HeaderState = HeaderPresent, F: FieldsState = FieldsUnfixed> { /* … */ }
pub struct BookAfterBids<'a, H: HeaderState = HeaderPresent> { /* same layout */ }

impl BookEncoder<'a, H, FieldsFixed> {
    pub fn bids(self, …) -> Result<BookAfterBids<'a>, …> { … }
    // no asks(): bids come first on the wire
}

Stage names: After{GroupPascal} (fuelFigures gives CarAfterFuelFigures). Reserved method names: reserved_name_clash_test. Product rationale: Wire order. Migration: Coming from sbe-tool.

API freeze decisions (pre-1.0)

Deliberate decisions on the generated public surface. Changing any of these after 1.0 is a major version. Golden file sbe/tests/golden/car_example.rs is the artifact for API shape review.

1. wrap takes message start (not body offset)

ergo-sbesbe-tool Rust
wrap offsetMessage start (first byte of header)Body offset (usually message_start + 8)
Field bytesat message_offset + HEADER_LENGTH + field_offsetat body_offset + field_offset

Decision: keep ergon semantics. One offset works for encode wrap, wrap_and_apply_header, and claim buffers. sbe-tool refugees who pass 8 for a frame at zero will mis-align every field, which is the top migration trap. Loud rustdoc on every generated wrap / wrap_and_apply_header / decode documents this; the book chapter Coming from sbe-tool is the full mapping.

2. *FixedFields is intentionally exhaustive

Generated CarFixedFields (and peers) are not #[non_exhaustive].

Decision: exhaustive is a feature. When the schema adds a fixed field, every fixed(&…) call site must update. Silent Default / ignored new fields would hide schema drift. Do not “fix” this with #[non_exhaustive] without a major-version design review.

3. Stage struct naming

Pattern: {Message}After{GroupPascal} for intermediate stages, {Message}Complete for the terminal encoder stage; decoder stages use {Message}DecoderAfter{…} similarly. Multi-word group names go through the same PascalCase path as other types (fuelFigures becomes FuelFigures, then CarAfterFuelFigures). Reserved-name clash coverage: sbe/tests/reserved_name_clash_test.rs.

Decision: keep named monomorphic stages (not Encoder<State = AfterBids>). Rationale: Type-state design note.

4. _unchecked companions are a supported opt-in

Decision: supported production opt-in after a proven trust boundary, not “benchmarking only”.

  • Default generation exposes the three-tier constructor boundary: try_* (Result), bare wrap (panic after extent proof), bare decode (panic if short, Err on wrong template/schema), and unsafe fn *_unchecked.
  • Safety contract: validate with try_decode / try_from / try_wrap / verify at trust edges; only *_unchecked may skip the extent proof (UB if wrong).
  • Hot loops after validation are an intended use case for the unchecked lane. Checked constructors remain the default for untrusted input.

See Trust boundaries.

5. Header marker default

H: HeaderState = HeaderPresent on encoder stages so the common full-frame path needs no turbofish. Body-only encoding uses wrap / HeaderAbsent explicitly.

6. No renames bundled with this note

This audit records decisions; it does not rename public generated types.

7. #[non_exhaustive] policy for generated structs

Struct#[non_exhaustive]Rationale
{Msg}FixedFieldsNo (exhaustive)Schema field additions must surface as compile errors (§2 above)
{Msg}EncoderNo (all fields pub(crate))Constructed by the generated wrap / wrap_and_apply_header
{Msg}DecoderNo (all fields pub(crate))Constructed by the generated try_decode / decode / wrap
{Msg}After{Element}No (all fields pub(crate))Only reachable through the consuming tail-stage chain
{Msg}CompleteNo (all fields pub(crate))Reachable after writing all tails
{Group}EncoderNo (all fields pub(crate))Constructed by the generated group closure
{Group}DecoderNo (fields are pub(crate))Constructed by generated iterator / wrap
{Group}EntryCompleteNo (fields pub(crate))Only produced by add_checked / complete()
{Msg}EncodedLengthNo (fields pub(crate))Constructed by compute_length()
{Msg}EncodedLengthAfter* / CompleteNo (fields pub(crate))Consuming stages, same as encoder
{Msg}SchemaNo (unit struct)Carries only consts
ConnectStepYesNew async-connect steps must not break exhaustiveness downstream
GenerateErrorYesFuture validation variants are additive
ParseErrorYes (1.0)Typed Io / Include causes; exhaustive matches need a wildcard

Decision: keep generated consumer-facing structs non-exhaustive via pub(crate) fields rather than #[non_exhaustive]. A downstream crate cannot construct one directly, so adding a field is not a breaking change. #[non_exhaustive] is reserved for public enums that will gain variants over time (GenerateError, ConnectStep). Any future rename lands in one release with CHANGELOG entries.

Why NullVal instead of Option

An SBE enum may declare a nullValue in the schema: an explicit wire sentinel that means “not present” / “not set”. When the schema doesn’t specify one, SBE defaults to the encoding type’s null sentinel: the maximum value for unsigned types (e.g. 255 for uint8) and the minimum value for signed types (e.g. -128 for int8).

nullValue / minValue / maxValue on a type or field must fit the declared primitive width. nullValue="256" on uint8 is a parse error, because it would otherwise collapse to 0 on the wire and make Some(0) indistinguishable from None. See Error diagnostics.

An early design tried wrapping every enum field in Option<EventCode> at the field site:

// Option approach: rejected
pub fn event_code(&self) -> Option<EventCode> { … }
pub fn set_event_code(&mut self, val: Option<EventCode>) { … }

This was rejected for three reasons:

  1. API complexity. Using Option<EventCode> at every access point forces every consumer to .unwrap() or match, even when the field is known to be populated. The NullVal approach gives you a plain EventCode type. If you care about null, check code == EventCode::NullVal; if you don’t, just use it. (The wire encoding itself would be compatible either way: None maps to the null sentinel, Some(v) maps to v. The issue is ergonomics, not wire format.)

  2. Generated code complexity. Every field site that uses Option<EventCode> needs value↔Option mapping in both accessor directions, inflating the generated code for no wire-format gain.

  3. Schema intent. The schema declares a null sentinel as part of the enum’s own value domain, not as a separate presence flag. A NullVal variant reflects that intent directly in the Rust type.

The chosen design adds a NullVal variant to every generated enum. It is the same size as any other variant and wire-compatible with sbe-tool. Its runtime cost is not measured here:

// ergo-sbe generated (conceptual)
pub enum EventCode {
    NullVal = 255,  // or schema-declared nullValue
    Ok = 200,
    Error = 400,
    Timeout = 408,
}
flowchart TD
    W["one wire byte, the schema null"] --> N["default: a NullVal variant on the enum"]
    W --> O["opt-in with_null_as_option: None"]
    N --> U["use the value, or compare with NullVal"]
    O --> M["match Option"]

The bytes do not change between the two. NullVal is the default because the schema’s null is a value of the enum, and because a caller who does not care about null should not have to match.

For an optional enum field (schema presence="optional") the accessor returns EventCode, with NullVal for null; it returns Option<EventCode> for a sinceVersion field or with with_null_as_option. Neither form allocates.

On encode, fixed(&FixedFields) always writes every fixed field: Some(v) writes the value and None writes the exact schema null wire image (including nested optional composite members). Dirty buffer reuse is therefore safe when you go through fixed. Prefer that path for whole-message encodes.

apply_nulls() remains on the unfixed encoder after wrap_and_apply_header when you set individual optional fields piecemeal instead of using FixedFields. See Encode and decode.

Opting into Option<T> with with_null_as_option

The NullVal is the right default, but some codebases prefer Option throughout. Use with_null_as_option to make generated enum accessors return Option<Enum>: NullVal maps to None, all other values to Some(v). Wire bytes are identical either way.

use ergo_sbe::{ConversionSelector, GenerationConfig};

// Individual enum → Option<Enum>
let config = GenerationConfig::new("msgs")
    .with_null_as_option(ConversionSelector::named_type("EventCode"));

// Every enum in the schema → Option<Enum>
let config = GenerationConfig::new("msgs")
    .with_all_enums_as_option();

Generated diff (individual setter):

// Default (NullVal)                         // with_null_as_option
pub fn code(&self) -> EventCode { … }   →   pub fn code(&self) -> Option<EventCode> { … }

The as_option() method is also generated on every enum for manual use: event_code.as_option() → Option<EventCode>.

Null-aware accessors on BooleanType

For BooleanType fields, ergon emits a {field}_bool() accessor alongside the standard enum getter. One name at every shape and location, the same name as the {field}_bool(v) encoder setter; it returns Result because the decode is fallible:

// Standard getter: returns the enum variant (raw wire discriminant).
pub fn available(&self) -> BooleanType { … }

// Null-aware: rejects NullVal (returns Err); Ok(true/false) otherwise.
pub fn available_bool(&self) -> Result<bool, DecodeError> { … }

// A `sinceVersion > 0` field can also be absent, so its getter adds the
// `Option` layer, the only shape difference, at message and group level:
pub fn added_later_bool(&self) -> Result<Option<bool>, DecodeError> { … }

For enums and other types, the NullVal variant remains the default. with_null_as_option (above) is the opt-in Option<T> mapping; the wire encoding is identical either way.

Generated enum mappings

with_enum_mapping maps an SBE enum onto an application enum that has no NullVal (see App types). There, NullVal is never turned into a variant: it decodes as sbe_rt::MappingError::NullEnum, or as None when the enum is also under with_null_as_option. Because the decoder folds an undeclared discriminant into NullVal, an unknown value reaches the mapping as that same NullVal.

Feature matrix

Scannable map of capabilities. Use the last column for samples and tests.

FeatureWhat it doesHow to use / more
build.rs codegenCompile-time schema to Rust module in OUT_DIRgenerate(SchemaSource::file("schemas/….xml"), config)?.write_to_out_dir()? · plain include! or sbe_mod!(name) · Quick start · codegen examples
Wire compatibilitySame on-wire layout as official SBEDual encode ergo vs sbe-tool · sbe_tool_wire_parity_test · golden fixtures · Benchmarks · baseline_test
Flyweight decodeZero-copy over &[u8]CarDecoder::try_from(buf)?; car.serial_number() · feature-tour
Composite wire image#[repr(transparent)] Engine([u8; N]) + LE accessors; flyweight defaultNot a repr(C) overlay · Core ideas · composite_layout_test
Per-field vs whole structFlyweight or *FixedFields / *DomainSingle field: flyweight · always fill fixed block: .fixed(&CarFixedFields { … }) · whole message owned: CarDomain · Core ideas · feature-tour
Stage-struct encode + closuresWire order as named monomorphic stages; groups via nested closuresbids(n, |g| g.add(|e| …))? · wrong order is a missing method · Core ideas · Recipes · Benchmarks
Consuming decode stagesDistinct after-stage decoder typesinto_bids(|lvl| …)? → into_asks(…)? → var-data · l3_consuming_stages_test
Decoder lanesRandom-access getters, staged into_*/skip_*, ordered callbacks, .memoized()Any-order &Decoder, wire-order walk, or one callback per tail · decode stages
Staged group shapeEntries with their own tails take a visit closure returning the entry’s completion; fixed-stride entries yield an iteratorOne pass either way: the completion is the next cursor, and fixed stride needs no measuring · Iterator only for &mut Iter, so for e in iter cannot drop the message tail · decode stages · l3_consuming_stages_test
Ordered lane (decoder.ordered())Callbacks in wire order at message and nested-entry level as sbe_rt::Ordered<S>; EntryInfo { index, count, block_length } per entryFaçade over the staged stages: same single traversal, same compile-time tail order · message fixed takes a fixed-fields-only view · callbacks return DecodeError · nested ordered() returns the parent completion directly · message chain ends on encoded_length_with_header() · decode stages · ordered_lane_test
Non-advancing counts and lengths<group>_count() / <field>_len() return Result<usize, DecodeError> without consuming a stageBase decoder, .memoized(), the immediately preceding stage, and group entries · 0 for absent versioned tails · iter.remaining_entries() returns usize · an existing primary getter suppresses the colliding convenience accessor (same yield for entry acting_* and ordered fixed) · decode stages
Three-tier constructorstry_* returns Result; bare wrap panics if short; bare decode panics if short and Err on wrong template/schema; unsafe *_uncheckedCarDecoder::try_decode(buf, 0)? · CarDecoder::verify(buf)? · demo_try_vs_trusted · Trust boundary
Placement metadataBuffer utils on get_metadata() so field names remaining / buffer / limit / message_offset stay natural (no _field rename)dec.get_metadata().remaining() · schema field remaining gives dec.remaining() · Generated code · reserved_name_clash_test
Exact buffer sizingSchema-aware length for nested/ragged msgs, no hand-calculated sizescompute_length_with_header() (fixed) · compute_length_with_header(…) (flat) · *EncodedLength (nested) · Core ideas · l3-book · encoded_length_api_test
Schema docs as rustdocXML descriptions become item docsdescription="…" / <description> / <comment> / <!-- --> · schema_docs_provenance_test
Display / DebugDiagnostic print (not wire format)println!("{car}"); · Display / Debug · demo_display_debug
NULL / MIN / MAXSchema sentinels as constsMODEL_YEAR_NULL · baseline_test
Version-aware fieldssinceVersion / acting versionOption or skip on older wire · baseline_test · multi_schema_versioning_test
Groups / nested groupsRepeating dimensionsbids(n, |g| g.add(…))? · l3-book · l3_orderbook_test
Bulk group encode / decodebulk_add(&[Entry]) / bulk_add_domain(&[EntryDomain]) / bulk_decode() -> Vec<Entry> for eligible flat groupsDTO re-encode selects the domain bulk path automatically when wire and domain fields match; measure against per-entry add() for your schema · group_encode_bench
Var-data / textLength-prefix; optional UTF-8/ASCIImanufacturer_as_str("Honda")? when a characterEncoding is declared, else manufacturer(b"Honda")? · feature-tour
Fixed arrays + bulk helpersArrays, put, pad string, copy-output_some_numbers(…) · vehicle_code_str · copy_vehicle_code · java_parity_features_test
Enums / sets / boolWire enums, bitsets, _boolavailable() / available_bool(true) · comprehensive_test
with_conversionWire type to any app type you implementprice_from(&Cents)? / price_as::<Cents>()? · Configuration · exchange-example
with_domain_typeWire type to one fixed Rust pathenc.price(d)?; let d = dec.price()? · l3-book · Configuration
Generated enum / composite mappingsSBE enum to your enum, composite to your struct, with renames; exhaustive both ways; NullVal and unknown values are MappingError::NullEnum.with_enum_mapping(EnumMapping::new("Side", "app::Side")) · .with_composite_mapping(CompositeMapping::new("Leg", "app::Leg")) · App types · type_mapping_test
Source traitsEncode your own type, groups and var-data included, with no DTO and no allocation.with_source_traits(true) · enc.encode_from(&order)? · Flyweight vs whole struct · source_trait_test
Send helpersClaim, encode, check length and header, then commit, aborting on any failure; try-claim or offer transportsOrderEncoder::send(claim, |enc| …)? · send_fixed · sbe_rt::OfferClaim · Aeron try_claim · claim_send_test
Domain DTOsOwned structs + re-encode; allocation-free automatic bulk write for eligible flat groups; var-data via [DomainVarData].with_domain_objects(DomainVarData::Strings) · Domain DTOs · domain_objects_test
AnyMessage + framesMulti-template + framed streamsAnyMessage::try_decode (bare decode is the same path today) · FrameCursor · demo_any_message
verifyFull tail bounds and var-data maxValue check (associated)CarDecoder::verify(buf)? · demo_try_vs_trusted
Schema identityId / version / hashesSCHEMA_ID, SCHEMA_HASH, SCHEMA_SHA256_HEX · generated module header
Multi-schema shared typesDedup across packages.with_shared_module + generate_multi · exchange-example · multi_schema_versioning_test
Keyword-safe namestype → type_.with_keyword_append_token("_") · java_parity_features_test
XSD-shaped validationOpt-in stricter check for schema authorsvalidate_against_sbe_xsd / SchemaSource::with_xsd_validation · xsd.rs
Zero-alloc hot pathFlyweights + caller buffers; bulk_decode() -> Vec and DomainVarData::Strings do allocateallocation_count_test
Property round-tripRandom messages encode then decodecargo test -p ergo-sbe --test proptest_roundtrip · proptest_roundtrip
NullVal as Option<T>Enum NullVal mapped to Option; wire-identical.with_null_as_option(…) / .with_all_enums_as_option() giving dec.code() -> Option<EventCode> · DTO None writes NullVal; bulk encode uses the same mapping · NullVal design note · Domain DTOs
Domain var-data typesCompactString (≤24B inline), SmolStr (O(1) clone), bytes::Bytes (shared).with_domain_objects(DomainVarData::CompactStrings), feature-gated: compact_str, smol_str, bytes · Feature integrations
Codec-level type accessorsinto_<field>_as_compact_str() / _as_smol_str() / _as_bytes() on consuming stagesFeature-gated behind compact_str, smol_str, bytes · Feature integrations
Chrono timestampsDateTime<Utc> / NaiveDateTime from uint64 + semanticType.with_domain_type(ConversionSelector::semantic_type("UTCTimestamp"), "chrono::DateTime<chrono::Utc>"), feature-gated: chrono · Timestamps
Lean constructorGenerationConfig::lean("minimal"): no Display/Debug/dispatch, explicit settings preservedlean() shorthand for new().profile(Lean) · GenerationConfig
Must-use lifecycle#[must_use] on SessionBuilder, AsyncClusterConnect, ClusterClaimCompile-time guard against discarded builder/connect/claim · SessionBuilder
PayloadTooLargeTyped error when header+payload exceeds Aeron maxClusterError::PayloadTooLarge { operation, requested, maximum } · Cluster client
Zero-alloc offer_partsFragmented path uses offer_parts gather, no heap, no payload copyStack header + borrowed payload · Cluster client
checked_deadlineFallible deadline: rejects zero/overflowClusterError::InvalidTimeout · Cluster client

Benchmarks

The maintained benchmarks show ergo-sbe is not slower than official sbe-tool on equal work. They are not a speed claim. Method, fairness rules, ceilings and the gate: sbe/BENCHMARKS.md.

QuestionAnswer
Run itjust bench (SBE), just bench-cluster (cluster)
What is gradedergon / sbe-tool, Criterion’s mean, highest ratio over 5 repeats, both LTO profiles
PassHighest ratio ≤ ceiling (1.00 for most pairs)
Inconclusive (also passes)Above the ceiling, but its confidence range overlaps the A/A control’s noise band
FailAbove the ceiling and outside the A/A band, or no A/A band measured
Tolerancenone (zero tolerance): no slack is added to a ceiling
Where results gotarget/bench-runs/<run-id>/ (just bench); target/criterion and target/bench-no-lto/criterion (just bench-cluster, overwritten)

This book records no benchmark result. Quote a ratio with its run id, commit, host, rustc and profile, or do not quote it.

Build your own code with lto = true and codegen-units = 1. Generated hot-path methods carry #[inline], so a non-LTO build can inline them too.

Also compare against your own previous release: see Methodology.

Benchmark methodology

The fairness rules and the gate are in sbe/BENCHMARKS.md; how a pair is built, its observation barriers and the A/A control in sbe/benchmarks/methodology.md. Two rules to keep in mind:

  • Treat a surprising ratio as a benchmark defect until wire parity, equal work, optimizer opacity, amplified timing, both LTO profiles and instruction counts agree.
  • Compare against your own previous release as well as against sbe-tool. Two releases can both pass the sbe-tool ceiling while the second is slower. just bench-ab <base> <branch> compares two commits on one host:
base
the base commit
branch
the commit under test
base-rebuilt
the base commit plus a layout salt:
the A/A control
The salt
an unused static and an unused
Bencher::iter, sorted before the
suite's own: the timed code starts
at other addresses. Each timed
symbol must move, and not by whole
cache lines (64 B x86, 128 B Apple).
No salt size moves them all: exit 4
base
base-rebuilt
branch
base-rebuilt
branch
base
branch
base
base-rebuilt
branch
base-rebuilt
base
base-rebuilt
base
branch
base
branch
base-rebuilt
within
spread of the base arm's per-round p50s
A/A
|p50(base-rebuilt) − p50(base)| / p50(base)
noise
max(within, A/A)
change
(p50(branch) − p50(base)) / p50(base)
UNSTABLE
A/A > 3 %: not judged either way, and not a pass
FAIL
change > noise and > the 1 % floor, or change > 3 %
PASS
otherwise
What it prints
n, min, p50, p99, p99.99 and max per arm, pooled over rounds
and repeats; then each row's verdict. Exit 1 on a FAIL, 3 when
only UNSTABLE rows remain, 2 on missing evidence.
Percentiles are of batch means (one Criterion sample's mean over a batch of
operations), not per-operation tails. Every max needs a cause before publishing.
Comparing two commits: three arms, rotated, with a layout salt
ergon book · Benchmark methodology (sbe/BENCHMARKS.md › Compare against your previous release)
Unchanged code moves when it is rebuilt, so the noise to beat is measured, not assumed.
built with
Rounds: each runs every arm once, in this order
1st
2nd
3rd
round 1
round 2
round 3
round 4
round 5
round 6
Rounds 1-3 rotate the order; 4-6 reverse it, so no arm runs twice in a row.
After 6 rounds every arm has run twice in each position and twice after each other arm.
--rounds must be a multiple of 3. Every run holds the bench lock and logs uptime.
The judge, per profile and scenario

Gate summary: Benchmarks.

Samples: teaching path

Standalone crates that exercise repository APIs. They are excluded from the workspace, set publish = false, and are not production reference implementations. They move with experimental APIs on purpose.

Start here (product teaching path)

StepSampleWhy
1SBE feature tourGolden path. Full feature map: stages, EncodedLength, checked constructors + verify, Display, DTO with DomainVarData::Strings, all three conversion styles
2aL3 order bookNested/ragged books; with_domain_type only; build-dep only (#[path] into src/generated/)
2bExchange exampleMulti-schema; with_conversion only; IPC + app TryFromSbe
3Codegen as a libraryGenerator as a library (no build.rs)
LaterCluster tutorial (in the cluster part)Connect, offer, poll, keep-alive, close
LaterCluster HA orderbook (cluster, in depth)Claim-based Cluster publishing of full L2 snapshots; epoch/sequence recovery across failover
LaterCluster RFQ (cluster, in depth)RFQ / auction codecs over Cluster
# 1: always start here
cargo run  --manifest-path samples/sbe-feature-tour/Cargo.toml

# 2: pick the conversion style you want in product code
cargo run  --manifest-path samples/l3-book/Cargo.toml
cargo test --manifest-path samples/exchange-example/Cargo.toml

Rule of thumb: one conversion style per schema type (with_domain_type or with_conversion, not both for the same selector).

Conversion: which sample uses what

SampleConfigDecode / encode surface
L3 order bookwith_domain_type onlydec.price()? returns Decimal; enc.price(d)?
Exchange examplewith_conversion onlydec.price_as::<T>()?; enc.price_from(&t)? (+ app TryFromSbe)
SBE feature tourAll three (different selectors)bool/timestamp concrete (Generated); Decimal generic (demo_conversion_only); ManualDecimal concrete + app impl (demo_domain_type_manual_impl)

Rule: one style per selector. with_domain_type already enables conversion; do not stack with_conversion on the same selector.

#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // A — generic converter: one wire type, many app types
    let _cfg =
        GenerationConfig::new("msgs").with_conversion(ConversionSelector::named_type("Decimal"));
}
#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // B — concrete mapping: one Rust type per wire type (already enables conversion)
    let _cfg = GenerationConfig::new("msgs").with_domain_type(
        ConversionSelector::named_type("Decimal"),
        "rust_decimal::Decimal",
    );
}

Rules

  • Keep every sample outside the workspace and unpublished.
  • Do not expose sample-only abstractions as product APIs.
  • Size SBE buffers from generated encoded-length APIs (prefer stack when const).
  • Propagate fallible operations with Result and ?.
  • Delete a sample when it no longer exercises a distinct repository behavior.

SBE feature tour

Standalone laboratory sample for ergo-sbe (publish = false). This is the crates.io / docs.rs teaching entry.

Conversion: three styles in one crate

build.rs uses different APIs for different selectors:

#![allow(unused)]
fn main() {
    let generated_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/generated");
    let config = ergo_sbe::GenerationConfig::new("feature_tour")
        .with_domain_objects(ergo_sbe::DomainVarData::Strings)
        .with_domain_type(
            ergo_sbe::ConversionSelector::named_type("BooleanType"),
            "bool",
        )
        .with_domain_type(
            ergo_sbe::ConversionSelector::semantic_type("UTCTimestamp"),
            "chrono::DateTime<chrono::Utc>",
        )
        .with_conversion(ergo_sbe::ConversionSelector::named_type("Decimal"))
        // Same shape as Decimal, but the app supplies the impl itself; see
        // demo_domain_type_manual_impl in src/lib.rs.
        .with_manual_domain_type(
            ergo_sbe::ConversionSelector::named_type("ManualDecimal"),
            "rust_decimal::Decimal",
        );

    ergo_sbe::generate(
        ergo_sbe::SchemaSource::file("schemas/feature-tour.xml"),
        config,
    )?
    .write_to(&generated_dir)?;
}

(The real build.rs; this code is compiled and tested in CI.)

The generated code is included via #[path = "generated/feature_tour.rs"], so no sbe_mod! is needed. See Build patterns.

SelectorConfigDecode APIEncode APIWho writes the impl?
BooleanTypewith_domain_type(.., "bool")dec.available()?enc.available(true)?ergo-sbe
UTCTimestampwith_domain_type(.., chrono)dec.timestamp()?enc.timestamp(t)?ergo-sbe
Decimal (Quote)with_conversion onlydec.price_as::<T>()?enc.price_from(&t)?app (generic, any T)
ManualDecimal (Quote)with_manual_domain_type(.., rust_decimal)dec.manual_price()?enc.manual_price(v)?app (one concrete type)

Runnable proof for the Decimal row: demo_conversion_only in src/lib.rs (uses both rust_decimal and a tiny FixedPrice adapter on the same buffer). Runnable proof for the ManualDecimal row: demo_domain_type_manual_impl has the same concrete manual_price(...)? signature DomainImpl::Generated would give you, but the impl TryFromSbe<ManualDecimal> / TryToSbe<ManualDecimal> above it are a literal copy-paste of the doc comment ergo-sbe put on the generated method (see with_conversion vs with_domain_type).

Quick rule

The comparison, including manual impls, is with_conversion vs with_domain_type. Call only one of the three for a given selector. The rows above are this sample’s selectors, not a second copy of that page.

Other samples:

SampleStyle
L3 order bookwith_domain_type only
Exchange examplewith_conversion only

Feature map and demos

FeatureDemo
Fixed message + compute_length_with_header()demo_fixed_heartbeat
Staged CarEncodedLengthdemo_car_size_and_encode
Consuming decoder stagesdemo_car_decode_stages
Owned DTOdemo_car_domain_dto
AnyMessagedemo_any_message
bulk_add (fixed-stride leaf group)demo_bulk_add
Checked decode / wrap / verifydemo_try_vs_trusted
Display / Debugdemo_display_debug
with_conversion onlydemo_conversion_only
with_manual_domain_typedemo_domain_type_manual_impl
All of the aboverun_all

Run

cargo run  --manifest-path samples/sbe-feature-tour/Cargo.toml
cargo test --manifest-path samples/sbe-feature-tour/Cargo.toml

After build, generated source is under src/generated/feature_tour.rs.

L3 order book

Deep nested / ragged L3 order-book sample for ergo-sbe. publish = false.

Conversion style: with_domain_type only

The comparison of with_domain_type and with_conversion is with_conversion vs with_domain_type. This sample uses only with_domain_type.

#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // B — concrete mapping: one Rust type per wire type (already enables conversion)
    let _cfg = GenerationConfig::new("msgs").with_domain_type(
        ConversionSelector::named_type("Decimal"),
        "rust_decimal::Decimal",
    );
}

(From book/examples/conversion-config.rs. Full L3 build.rs: l3-book.)

Generated API (concrete):

enc.price(rust_decimal::Decimal::new(100, 0))?;
let p: rust_decimal::Decimal = dec.price()?;
let ts: DateTime<Utc> = dec.exchange_timestamp()?;

with_domain_type already enables conversion for that selector. Do not also call with_conversion(Decimal) here; it would not change the surface.

NeedUse
Concrete price() -> DecimalThis sample (with_domain_type)
Generic price_as::<T>() / app adaptersExchange Example (with_conversion)
Side-by-side both stylesSBE Feature Tour

Encoding: size exactly, then write

Nothing here guesses a buffer size. The staged L3BookEncodedLength builder walks the same shape the encoder will write (bids_ragged with a nested orders count per level, then asks_ragged, then the var-data symbol) and returns the exact header-inclusive length:

pub fn book_encoded_length(
    bids: &Side<'_>,
    asks: &Side<'_>,
    symbol: &str,
) -> Result<usize, sbe_rt::EncodeError> {
    let after_bids = L3BookEncoder::compute_length().bids_ragged(bids.len() as u16, |g| {
        for (_, _, orders) in bids {
            g.add()?.orders(|og| {
                og.uniform(orders.len())?;
                Ok(())
            })?;
        }
        Ok(())
    })?;
    let after_asks = after_bids.asks_ragged(asks.len() as u16, |g| {
        for (_, _, orders) in asks {
            g.add()?.orders(|og| {
                og.uniform(orders.len())?;
                Ok(())
            })?;
        }
        Ok(())
    })?;
    let complete = after_asks.symbol(symbol.len())?;
    Ok(complete.encoded_length_with_header())
}

_ragged is the point for an order book: every level has a different number of orders, so the count cannot be multiplied out. g.add()?.orders(|og| …) declares one level and then that level’s own order count.

The encoder then writes into a buffer of precisely that length, in wire order, one chained expression:

pub fn encode_book(
    buf: &mut [u8],
    bids: &Side<'_>,
    asks: &Side<'_>,
    symbol: &str,
) -> Result<usize, sbe_rt::EncodeError> {
    let complete = L3BookEncoder::try_wrap_and_apply_header(buf, 0)?
        .fixed(&L3BookFixedFields {
            exchange_timestamp: 1_720_000_000_000_000_000u64,
            sequence: 42,
            is_active: true.into(),
        })
        .bids(bids.len() as u16, |g| {
            for (price, size, orders) in bids {
                g.add(|mut e| {
                    e.price(*price)
                        .map_err(|_| sbe_rt::EncodeError::DomainConversionFailed {
                            field: "price",
                            reason: "conversion",
                        })?;
                    e.size(*size)
                        .map_err(|_| sbe_rt::EncodeError::DomainConversionFailed {
                            field: "size",
                            reason: "conversion",
                        })?;
                    e.orders(orders.len() as u16, |og| {
                        for (oid, qty) in *orders {
                            let raw_qty =
                                SbeDecimal::new(qty.mantissa() as i64, -(qty.scale() as i8));
                            og.add_struct(&L3BookBidsOrdersEntry {
                                order_id: *oid,
                                quantity: raw_qty,
                            })?;
                        }
                        Ok(())
                    })
                })?;
            }
            Ok(())
        })?
        .asks(asks.len() as u16, |g| {
            for (price, size, orders) in asks {
                g.add(|mut e| {
                    e.price(*price)
                        .map_err(|_| sbe_rt::EncodeError::DomainConversionFailed {
                            field: "price",
                            reason: "conversion",
                        })?;
                    e.size(*size)
                        .map_err(|_| sbe_rt::EncodeError::DomainConversionFailed {
                            field: "size",
                            reason: "conversion",
                        })?;
                    e.orders(orders.len() as u16, |og| {
                        for (oid, qty) in *orders {
                            let raw_qty =
                                SbeDecimal::new(qty.mantissa() as i64, -(qty.scale() as i8));
                            og.add_struct(&L3BookAsksOrdersEntry {
                                order_id: *oid,
                                quantity: raw_qty,
                            })?;
                        }
                        Ok(())
                    })
                })?;
            }
            Ok(())
        })?
        .symbol_as_str(symbol)?;
    Ok(complete.encoded_length_with_header())
}

Both functions end with encoded_length_with_header(), and the tests assert the two agree: a length that does not match the bytes written is a bug in the sizing API, not something to paper over with a larger buffer.

symbol declares characterEncoding="ASCII" in the schema, so the generated encoder carries a symbol_as_str(&str) setter alongside the raw symbol(&[u8]) one. Every caller here always holds text, so encode_book takes symbol: &str and writes through symbol_as_str. The ASCII check runs before any byte is written rather than leaving it to the caller. Both setters write identical bytes for the same text; reach for the raw symbol(&[u8]) setter only when the caller genuinely starts from bytes.

let len = book_encoded_length(bids, asks, symbol)?;   // exact, header-inclusive
let mut storage = vec![0u8; len];                     // no oversize, no truncate
let actual = encode_book(&mut storage, bids, asks, symbol)?;
assert_eq!(len, actual);

See Exact sizing and Buffer sizing.

flowchart LR
    H["header and fixed fields"] --> B["bids"]
    B --> BO["orders, per bid"]
    BO --> A["asks"]
    A --> AO["orders, per ask"]
    AO --> S["symbol"]

symbol is last. A random-access read of it walks every order on the way there, then can walk them again. A staged decode visits each tail once, in this order, and cannot name symbol any earlier.

Decoding: random access or one staged chain

L3Book is the shape that makes the decoder lanes worth distinguishing: two sibling groups, each entry carrying a nested orders group, then a trailing var-data symbol. Reaching symbol means walking past every order of every level.

tests/l3_tests.rs encodes one ragged fixture and decodes it through the generated lanes, asserting they produce an identical snapshot. Note what the snapshot holds: the schema’s domain types (rust_decimal::Decimal, DateTime<Utc>, bool) because that is what with_domain_type generates, and a borrowed &'a str for symbol, since copying it would defeat the flyweight.

/// Everything the fixture contains, in wire order, in the schema's *domain*
/// types, not its wire types.
///
/// This sample generates with `with_domain_type`, so `price` is
/// `rust_decimal::Decimal`, `exchangeTimestamp` is `DateTime<Utc>` and
/// `isActive` is `bool`. Comparing at that level is what proves the
/// conversions round-trip; comparing raw mantissas would pass even if the
/// domain layer were broken.
///
/// `symbol` is borrowed, not owned: every lane hands back `&'a str` pointing
/// into the wire buffer. Copying it would defeat the flyweight. The `Vec`s
/// are the *test's* comparison scaffolding (a decode has to materialise
/// something to compare), not part of the decode path, which allocates
/// nothing.
#[derive(Debug, PartialEq, Eq)]
struct Snapshot<'a> {
    timestamp: chrono::DateTime<chrono::Utc>,
    sequence: u64,
    is_active: bool,
    /// `(price, size, [(order_id, quantity)])` per level.
    bids: Vec<OwnedLevel>,
    asks: Vec<OwnedLevel>,
    symbol: &'a str,
}

/// A decoded level, owned so lanes can be compared. The decode itself borrows
/// (see `best_bid_and_depth` for the shape a hot path actually uses).
type OwnedLevel = (Rd, Rd, Vec<(u64, Rd)>);
/// Ragged on purpose: 3 bid levels with 2/1/3 orders and 2 ask levels with
/// 1/2. A uniform fixture would let a lane compute entry positions by
/// multiplication and still look correct.
fn fixture() -> (Vec<u8>, Vec<OwnedLevel>, Vec<OwnedLevel>) {
    let o_b1 = [(101u64, d(5)), (102, d(7))];
    let o_b2 = [(103u64, d(25))];
    let o_b3 = [(104u64, d(1)), (105, d(2)), (106, d(3))];
    let bids: &[l3_book::Level<'_>] = &[
        (d(50800), d(15), &o_b1),
        (d(50750), d(40), &o_b2),
        (d(50700), d(60), &o_b3),
    ];
    let o_a1 = [(201u64, d(10))];
    let o_a2 = [(202u64, d(20)), (203, d(30))];
    let asks: &[l3_book::Level<'_>] = &[(d(50850), d(20), &o_a1), (d(50900), d(35), &o_a2)];
    let symbol = "BTCUSDT";

    // Exact sizing through the staged builder, then encode into a buffer of
    // precisely that length: no oversize, no truncate.
    let len = l3_book::book_encoded_length(bids, asks, symbol).expect("length");
    let mut storage = vec![0u8; len];
    let actual = l3_book::encode_book(&mut storage, bids, asks, symbol).expect("encode");
    assert_eq!(len, actual, "computed length must match encoded length");
    let mut short = vec![0u8; len - 1];
    assert!(
        l3_book::encode_book(&mut short, bids, asks, symbol).is_err(),
        "one byte short must fail, not truncate"
    );

    let own = |lv: &(Rd, Rd, &[(u64, Rd)])| (lv.0, lv.1, lv.2.to_vec());
    (
        storage,
        bids.iter().map(own).collect(),
        asks.iter().map(own).collect(),
    )
}

Random access: any order, Sync, re-walks

/// Lane 1: random access (the base decoder from `try_decode`).
///
/// Getters may be called in any order and the decoder is `Sync`. Each
/// dynamic-tail getter re-walks from the fixed block, so reading `bids`,
/// `asks` and `symbol` walks the bid orders three times over. Correct
/// everywhere, cheapest when you want one or two fields.
fn decode_random_access(wire: &[u8]) -> Result<Snapshot<'_>, Box<dyn std::error::Error>> {
    let dec = L3BookDecoder::try_decode(wire, 0)?;

    // Deliberately out of wire order: symbol (the last tail) first, then back
    // to the groups. Only a lane that resolves tails independently can do
    // this. The `&str` borrows the wire buffer, so nothing is copied.
    let symbol = dec.symbol_as_str()?;

    let mut bids = Vec::new();
    for level in dec.bids()? {
        let level = level?;
        let mut orders = Vec::new();
        // `orders` is fixed-stride, so its whole region was proven in bounds
        // when the group was entered and the iterator yields entries directly.
        // The outer `bids`/`asks` iterators yield `Result` because a dynamic
        // entry's extent can only be known once it is reached.
        for order in level.orders()? {
            orders.push((order.order_id(), order.quantity()?));
        }
        bids.push((level.price()?, level.size()?, orders));
    }

    let mut asks = Vec::new();
    for level in dec.asks()? {
        let level = level?;
        let mut orders = Vec::new();
        for order in level.orders()? {
            orders.push((order.order_id(), order.quantity()?));
        }
        asks.push((level.price()?, level.size()?, orders));
    }

    Ok(Snapshot {
        timestamp: dec.exchange_timestamp()?,
        sequence: dec.sequence(),
        is_active: dec.is_active()?,
        bids,
        asks,
        symbol,
    })
}

Note it reads symbol (the last tail) first, then goes back to the groups. Only a lane that resolves each tail independently can do that. The cost is that every dynamic-tail getter re-walks from the fixed block.

Staged: wrong order is a compile error

/// Sequential decode with `into_*` / `skip_*`, compile-time order. The group
/// iterator is the stage: `into_asks` skips unread bids.
fn decode_staged(wire: &[u8]) -> Result<Snapshot<'_>, Box<dyn std::error::Error>> {
    let dec = L3BookDecoder::try_decode(wire, 0)?;
    let timestamp = dec.exchange_timestamp()?;
    let sequence = dec.sequence();
    let is_active = dec.is_active()?;

    // Levels carry a nested `orders` group, so they have no stride and take a
    // visit closure: the completion it returns is where the next level starts.
    // `orders` entries are fixed-stride, so they are a plain iterator.
    let mut bids = Vec::new();
    let mut asks = Vec::new();
    let (symbol, _complete) = dec
        .into_bids(|level| -> Result<_, Box<dyn std::error::Error>> {
            let price = level.price()?;
            let size = level.size()?;
            let mut orders = Vec::new();
            let mut order_iter = level.into_orders()?;
            for order in &mut order_iter {
                orders.push((order.order_id(), order.quantity()?));
            }
            bids.push((price, size, orders));
            Ok(order_iter.finish()?)
        })?
        .into_asks(|level| -> Result<_, Box<dyn std::error::Error>> {
            let price = level.price()?;
            let size = level.size()?;
            let mut orders = Vec::new();
            let mut order_iter = level.into_orders()?;
            for order in &mut order_iter {
                orders.push((order.order_id(), order.quantity()?));
            }
            asks.push((price, size, orders));
            Ok(order_iter.finish()?)
        })?
        .into_symbol_as_str()?;

    Ok(Snapshot {
        timestamp,
        sequence,
        is_active,
        bids,
        asks,
        symbol,
    })
}

into_symbol exists only on the stage reached after asks completes, so the out-of-order read above is not expressible here. One wire-order pass.

Memoized: any order, each boundary walked once

/// Lane 3: memoized (`decoder.memoized()`).
///
/// Same getter names as the base lane, plus a progressive cache of discovered
/// tail boundaries. Read here in the worst order for the base lane: symbol
/// first, then back to the groups, then symbol again. That is exactly the
/// shape the cache exists for.
fn decode_memoized(wire: &[u8]) -> Result<Snapshot<'_>, Box<dyn std::error::Error>> {
    let dec = L3BookDecoder::try_decode(wire, 0)?.memoized();

    let symbol = dec.symbol_as_str()?;

    let mut bids = Vec::new();
    for level in dec.bids()? {
        let level = level?;
        let mut orders = Vec::new();
        for order in level.orders()? {
            orders.push((order.order_id(), order.quantity()?));
        }
        bids.push((level.price()?, level.size()?, orders));
    }

    let mut asks = Vec::new();
    for level in dec.asks()? {
        let level = level?;
        let mut orders = Vec::new();
        for order in level.orders()? {
            orders.push((order.order_id(), order.quantity()?));
        }
        asks.push((level.price()?, level.size()?, orders));
    }

    // Re-reading a tail is free once its boundary is known: the base lane
    // would re-walk every bid and ask order to get back here.
    assert_eq!(dec.symbol_as_str()?, symbol, "re-read must be identical");

    Ok(Snapshot {
        timestamp: dec.exchange_timestamp()?,
        sequence: dec.sequence(),
        is_active: dec.is_active()?,
        bids,
        asks,
        symbol,
    })
}

Same getter names as random access. Read in the order shown (symbol, then back to the groups, then symbol again), the base lane re-walks every bid and ask order to return to symbol; this lane reuses the boundary it already found. Build it once and pass &L3BookMemoizedDecoder around: calling .memoized() in each function creates a separate empty cache.

Ordered: one spelling, all the way down

/// Lane 4: ordered (`decoder.ordered()`). One callback per tail, in wire
/// order, with the *same spelling* at every tail, plus an `EntryInfo` giving
/// each entry's position.
///
/// Compare with `decode_staged`: there, `bids` takes a visit closure and
/// `orders` is an iterator, because their shapes genuinely differ. Here every
/// message-level tail (fixed block, both groups and the var-data) reads the
/// same way. That uniformity is why this lane exists: code that walks whole
/// messages writes one form instead of branching on each tail's shape.
///
/// It goes all the way down. A `bids` level carries its own tail (the nested
/// `orders` group), so it has an `ordered()` of its own, and the spelling does
/// not change at the entry boundary. Returning that nested walk is the
/// completion the parent owes, with no `.done()` on the way out. The message
/// chain ends on `encoded_length_with_header()`, like encode.
///
/// The staged `level.into_orders()` iterator is still generated beside it and
/// is still the better tool when you want to `break` early: `orders` is
/// fixed-stride, so its iterator is an `ExactSizeIterator` and stopping short
/// still reaches the next tail by arithmetic. The lane adds a spelling; it
/// removes nothing.
///
/// `EntryInfo::count` is the wire-declared `numInGroup`, read from the group's
/// dimension header before the walk starts, so the `Vec` is sized once rather
/// than grown. It costs no scan. `bids` and `asks` still need separate bodies
/// because their entry decoders are distinct types; the lane unifies how a
/// tail is *reached*, not what its entries are.
fn decode_ordered(wire: &[u8]) -> Result<Snapshot<'_>, Box<dyn std::error::Error>> {
    // Ordered callbacks return `DecodeError`; a domain getter fails with its
    // conversion's own error, mapped the way the generated DTO maps it.
    fn domain<T, E>(field: &'static str, r: Result<T, E>) -> Result<T, sbe_rt::DecodeError> {
        r.map_err(|_| sbe_rt::DecodeError::DomainConversionFailed {
            field,
            reason: "domain conversion rejected wire value",
        })
    }

    let mut timestamp = None;
    let mut sequence = 0u64;
    let mut is_active = false;
    let mut bids: Vec<OwnedLevel> = Vec::new();
    let mut asks: Vec<OwnedLevel> = Vec::new();
    let mut symbol: Option<&str> = None;

    let len = L3BookDecoder::try_decode(wire, 0)?
        .ordered()
        .fixed(|d| {
            timestamp = Some(domain("exchange_timestamp", d.exchange_timestamp())?);
            sequence = d.sequence();
            is_active = domain("is_active", d.is_active())?;
            Ok(())
        })?
        .bids(|level, info| {
            if info.is_first() {
                bids.reserve_exact(info.count);
            }
            let price = domain("price", level.price())?;
            let size = domain("size", level.size())?;
            // Nested `ordered()` returns the completion the parent owes,
            // with no `.done()` on the way out.
            let mut orders = Vec::new();
            let complete = level.ordered().orders(|order, _oinfo| {
                orders.push((order.order_id(), domain("quantity", order.quantity())?));
                Ok(())
            })?;
            bids.push((price, size, orders));
            Ok(complete)
        })?
        .asks(|level, info| {
            if info.is_first() {
                asks.reserve_exact(info.count);
            }
            let price = domain("price", level.price())?;
            let size = domain("size", level.size())?;
            let mut orders = Vec::new();
            let complete = level.ordered().orders(|order, _oinfo| {
                orders.push((order.order_id(), domain("quantity", order.quantity())?));
                Ok(())
            })?;
            asks.push((price, size, orders));
            Ok(complete)
        })?
        .symbol_as_str(|s| {
            symbol = Some(s);
            Ok(())
        })?
        .encoded_length_with_header();
    debug_assert_eq!(len, wire.len());

    Ok(Snapshot {
        timestamp: timestamp.ok_or("fixed callback must run")?,
        sequence,
        is_active,
        bids,
        asks,
        symbol: symbol.ok_or("symbol callback must run")?,
    })
}

Compare it with the staged lane above: there bids takes a visit closure and orders is an iterator, because those two shapes genuinely differ. Here every message-level tail (fixed block, both groups, then the var-data) reads the same way, and each entry callback also receives an EntryInfo carrying index, the wire-declared count, and the acting block_length. Count and block length come from the group decoder the staged walk already opened; the index advances with the walk. Using info.count to reserve space needs no entry scan. Empty groups never deliver EntryInfo; <group>_count() on the ordered stage still reports the declared count.

It recurses. A bids level carries its own tail (the nested orders group), so the level decoder has an ordered() too, and the callback above uses it. The spelling does not change at the entry boundary, and returning that nested walk is the completion the parent closure owes; there is no .done() on the way out. An entry with no tails of its own (a fixed-stride entry) has nothing to order and gets no lane. An entry whose existing getter is named ordered also keeps its getter and uses the staged spelling for its tails.

The staged spelling is still generated beside it: level.into_orders() hands back a real ExactSizeIterator you can break out of and still reach the next tail by arithmetic. Pick the iterator when you want to stop early and continue at the next tail, or the ordered lane when you want callbacks throughout.

It is a façade over the staged stages, so it keeps their single traversal and compile-time tail order. The message chain ends on encoded_length_with_header(), like encode. Dynamic groups fill EntryInfo from that walk; fixed-stride groups reuse the iterator’s count and stride. Neither shape pre-scans entries or re-opens the dimension header. The optimizer and measured workload determine the callback wrapper’s final cost. Message-level fixed receives a fixed-fields-only view. Callbacks return DecodeError; convert to an application error after the walk.

On a hot path, collect nothing

The four functions above build owned Vecs because a test has to materialise something to compare. Real consumption does not: the decoders are flyweights over the wire buffer, &str and &[u8] borrow from it, and a full nested walk needs no allocation at all.

/// The shape you actually want on a hot path: no `Vec`, no `String`, no copy.
///
/// The lane functions above build owned collections because a test has to
/// materialise something to compare. Real consumption does not. Here every
/// level and every nested order is visited, `symbol` is used as a borrowed
/// `&str`, and the only state is a handful of scalars in registers; the
/// generated decoders are flyweights over the wire buffer and allocate
/// nothing, so this whole walk is allocation-free.
///
/// A price is compared as a price, not as a raw mantissa: the wire `Decimal`
/// carries its own exponent, and `1.00` (mantissa 100, exponent −2) is less
/// than `99` (mantissa 99, exponent 0). The fallible domain conversion is the
/// one place that knows how to align the two.
fn best_bid_and_depth(wire: &[u8]) -> Result<(Rd, u64, usize, &str), sbe_rt::DecodeError> {
    let mut best_bid: Option<Rd> = None;
    let mut total_orders = 0u64;
    let mut levels = 0usize;

    let (symbol, _done) = L3BookDecoder::try_decode(wire, 0)?
        .into_bids(|level| -> Result<_, sbe_rt::DecodeError> {
            levels += 1;
            let px =
                level
                    .price()
                    .map_err(|reason| sbe_rt::DecodeError::DomainConversionFailed {
                        field: "price",
                        reason,
                    })?;
            if best_bid.is_none_or(|b| px > b) {
                best_bid = Some(px);
            }
            let mut orders = level.into_orders()?;
            // Fixed stride, so the count is exact without walking.
            let entries = &mut orders;
            total_orders += entries.len() as u64;
            orders.finish()
        })?
        .skip_asks()?
        .into_symbol_as_str()?;

    Ok((
        best_bid.ok_or(sbe_rt::DecodeError::DomainConversionFailed {
            field: "bids",
            reason: "no bid levels",
        })?,
        total_orders,
        levels,
        symbol,
    ))
}

hot_path_walk_borrows_everything asserts the returned &str points inside the wire buffer rather than at a copy. Repository-wide, allocation_count_test pins the same property for generated decode under a counting allocator.

Which one

You are doingLane
Reading a couple of fields, or one tailrandom access (smallest, Sync)
Decoding the whole book in wire orderstaged into_* (one traversal, compile-time tail order)
Several helpers reading multiple tails, same thread.memoized()
Walking whole messages with uniform code, or needing entry position.ordered() (one callback per tail, EntryInfo per entry)

Full comparison, including how each differs from sbe-tool’s single limit cursor: Decoder lanes.

Layout

PathRole
schemas/l3-book.xmlNested bids/asks, orders, var-data tails
build.rsgenerate(..)?.write_to(..) into src/generated/ + domain objects / with_domain_type (build-dep only)
src/lib.rs#[path = "generated/l3_codec.rs"] + EncodedLength helpers
src/main.rsRunnable demos
tests/l3_tests.rsRound-trips, exact-length proofs, and the four-lane decode comparison

Run

cargo run  --manifest-path samples/l3-book/Cargo.toml
cargo test --manifest-path samples/l3-book/Cargo.toml

Exchange example

Multi-schema exchange-shaped sample. It uses with_conversion only for Decimal, with no with_domain_type. publish = false. The Aeron calls it makes (connect, offer, poll, close) one by one: rusteron-client.

Conversion style

with_conversion versus with_domain_type is with_conversion vs with_domain_type. This sample uses only with_conversion.

#![allow(unused)]
fn main() {
    use ergo_sbe::{ConversionSelector, GenerationConfig};
    // A — generic converter: one wire type, many app types
    let _cfg =
        GenerationConfig::new("msgs").with_conversion(ConversionSelector::named_type("Decimal"));
}

(From book/examples/conversion-config.rs. Full multi-schema build.rs: exchange-example.)

That emits generic methods. The app supplies TryFromSbe / TryToSbe:

// encode: app Decimal to wire
e.price_from(&d)?;

// decode: wire to app Decimal
let d: rust_decimal::Decimal = level.price_as()?;

You still have wire accessors (price_value / price_wire). You do not get a concrete price() -> rust_decimal::Decimal; that requires with_domain_type(..., "rust_decimal::Decimal") (see L3 order book).

SampleConfig
This cratewith_conversion only
L3 order bookwith_domain_type only
SBE feature tourboth (demo_conversion_only is conversion-only)

Run

cargo test --manifest-path samples/exchange-example/Cargo.toml
just run-sample           # its messages, live, in ergo-aeron
just run-sample archive   # the same, recorded by a Java Aeron Archive

What run-sample starts, its keys and what each mode needs: samples/README.md.

JSON labels from schema marks

The sample’s build.rs registers a hook that reads jsonValue marks off each enum’s validValue elements at generation time and emits a json_label() accessor. Enums whose validValues are all labelled get the method; partially labelled or unmarked enums are skipped, so the other two schemas generate byte-identical code.

// tests/json_label_test.rs
use exchange_example::<venue>_spot::AccountType; // the shipped venue schema's module

assert_eq!(AccountType::Spot.json_label(), "SPOT");
assert_eq!(AccountType::NullVal.json_label(), "UNKNOWN");

Worked example: extension XML

This sample is the worked example for Extension XML. Its build.rs handles the extension marks of the published venue schema it ships (the first file in schemas/, generated as the <venue>_spot module) through the generic API only, keyed on that schema’s own attribute names:

    // Extension marks through the generic API only, keyed on the venue
    // schema's own attribute names: labels from `json_label_hook`,
    // mantissa/exponent pairs from the `pairs` recipe (group mantissas with
    // message-level exponents included), and every mark (`jsonPath`,
    // `jsonDefaultValue`, `jsonOmitNull`, ...) as a const. The other two
    // sample schemas carry no marks, so their output does not change.
    let config = config
        .with_hook(json_label_hook)
        .with_try_hook(ext_recipes::pairs("exponent", "with_exponent"))
        .with_try_hook(json_hook)
        .with_extension_consts(true);

ext_recipes is ergo-sbe’s venue-neutral example-hook file (sbe/tests/common/ext_recipes.rs), included with #[path]. The other two sample schemas carry no marks, so their generated code does not change.

MarkGenerated
jsonValue on validValuesFilterType::MaxAsset.json_label() == "MAX_ASSET" (json_label_hook) and FilterType::MAX_ASSET_JSON_VALUE; as_str stays "MaxAsset"
exponent naming a field of the same blockmax_qty_with_exponent() -> (i64, i8), exactly what both accessors return
exponent naming a message field from a groupbid.price_with_exponent(&message) -> (i64, i8) on the depth response’s entries
jsonPath, jsonDefaultValue, jsonOmitNullMaxAssetFilterSchema::MAX_QTY_JSON_PATH == "limit", TPlusSellFilterSchema::END_TIME_JSON_DEFAULT_VALUE == "-1", the group-level ExchangeInfoResponseSchema::SORS_JSON_OMIT_NULL == "true"

The assertions live in tests/extension_fixture_test.rs. cargo run --example sbe_text decodes a filter message and prints the label, an exact mantissa × 10^exponent rendering and the asset text.

SBE responses back to the venue’s JSON

The venue’s REST API answers each request as JSON or, on request, as SBE. Its schema’s marks record how one maps to the other: jsonPath the JSON key ([] an array position, .. the group’s array is the parent value), exponent the field that scales a mantissa into a decimal string, jsonDefaultValue the JSON for an absent optional. A try-hook in build.rs (json_hook) reads those marks and the decoder accessors named in the hook context, and emits a write_json method on each covered response decoder, group decoder and entry decoder; an entry whose mantissa is scaled by a message-level exponent takes the enclosing decoders as arguments. src/sbe_json.rs formats values (exact decimals, integer arithmetic only) and dispatches on the template id.

# Recorded real responses render to JSON equal to the venue's own JSON
cargo test --manifest-path samples/exchange-example/Cargo.toml --test json_fixture_test
# Render a saved SBE response body
cargo run --manifest-path samples/exchange-example/Cargo.toml --example sbe_json -- <file.sbe>

tests/fixtures/ holds one SBE body and the JSON body of the same public market-data request per endpoint (order book, trades, aggregate trades, klines, average price, price and book tickers); the test compares them as JSON values. scripts/ has the live check that recorded them. The sample’s README section in samples/README.md records what each mark is for and what recording found.

Codegen as a library

Generator-API examples showing how to call ergo-sbe as a library to generate and inspect codecs programmatically (without a build.rs).

The other samples (l3-book, sbe-feature-tour, exchange-example) all use build.rs to generate codecs at compile time and then exercise them end-to-end. These examples complement them by showing the generator API itself, which is useful for tooling, golden-file workflows, and understanding what the generator produces.

From schema XML to generated Rust

Animation, in words: it follows a small illustrative Quote schema (two fixed fields, a legs group and a venue var-data field), not the car schema the examples use. generate(source, config) is parse, Schema::from_ir, then Generator::generate.

  1. An optional XSD shape check (with_xsd_validation(), off by default) runs on the root document’s text before anything is parsed.
  2. parse turns the XML into one flat stream of 46 Begin/End tokens, with each type reference inlined.
  3. Still inside parse, resolve_schema fills the same tokens in place: price at offset 0, qty at 8, a block length of 12, a group entry length of 8, null/min/max defaults, and checks for duplicate template ids.
  4. Schema::from_ir only wraps the result. The Generator checks the GenerationConfig, then splits the tokens into typed messages, groups and fields.
  5. One decoder call per message emits QuoteDecoder, the staged into_* chain, ordered() and memoized(). The encoder call emits the type-state QuoteEncoder and compute_encoded_length(legs_count, venue_len), which is 40 bytes for 2 legs and a 4-byte venue (48 with the header).
  6. syn and prettyplease produce one in-memory module, which is where these examples read set.modules().
  7. write_to_out_dir() writes $OUT_DIR/quote.rs (all or none) and prints rerun-if-changed for the schema. sbe_mod!(quote) includes it, and a plain include! does the same without a normal dependency on ergo-sbe.

If a field names an undefined type, parse stops there with ergo_sbe::schema_parse::invalid and the line underlined. resolve and the generator never run. All of this happens at build time, so a running program never parses a schema. The cost is a rebuild for each schema change, and an sbe_rt in every module unless you use with_shared_module or with_external_sbe_rt. The book records no timings for the pipeline.

Examples

# From the repository root; this crate is not a workspace member.
cargo run --manifest-path samples/sbe-codegen-examples/Cargo.toml --example flyweight
cargo run --manifest-path samples/sbe-codegen-examples/Cargo.toml --example domain_objects
cargo run --manifest-path samples/sbe-codegen-examples/Cargo.toml --example l3_nested
cargo run --manifest-path samples/sbe-codegen-examples/Cargo.toml --example dump_gen

What each shows

ExampleDemonstrates
flyweightGenerator::generate() with default config, giving zero-copy flyweights
domain_objectswith_domain_objects(DomainVarData::Strings): owned DTOs (String var-data) + try_from_decoder
l3_nestedThe full type graph for 3-level nested groups (L1, L2 and L3 entry types)
dump_genThe complete generated Rust source for inspection

All examples parse the canonical car schema.

Build patterns

Generated codecs ship their own embedded sbe_rt module. Linking the app does not require ergo-sbe unless you use its macros or call the generator library at runtime.

Patternbuild-dependenciesdependenciesTypical use
Build only (samples default)ergo-sbenonegenerate(..)?.write_to("src/generated") writes src/generated/ (gitignored, unpublished), included with #[path = "generated/….rs"]
OUT_DIR onlyergo-sbenonegenerate(..)?.write_to_out_dir() + include!(concat!(env!("OUT_DIR"), …)); the product shape without macros
Build + runtime (product default)ergo-sbeergo-sbegenerate(..)?.write_to_out_dir() + sbe_mod! (expands to that include!); this is what cluster/build.rs and the introduction do
Runtime onlynoneergo-sbeCall generate, or parse + Generator, as a library (no build.rs)

Seeing generated code (without committing it)

include!(concat!(env!("OUT_DIR"), …)) and sbe_mod! put files under a hashed path like target/debug/build/<crate>-<hash>/out/….rs, which is awkward to open by hand.

Samples instead write to a stable, local path:

samples/<name>/src/generated/*.rs   # created on cargo build, gitignored
  1. cargo build --manifest-path samples/sbe-feature-tour/Cargo.toml
  2. Open samples/sbe-feature-tour/src/generated/feature_tour.rs
  3. From app code, Go to definition on CarEncoder / etc. should land there

Root .gitignore has **/src/generated/. Do not commit those trees (a large exchange schema generates several MB). Rebuild after a clean clone.

  // build.rs
  let out = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/generated");
  ergo_sbe::generate(ergo_sbe::SchemaSource::file("schemas/messages.xml"), config)?
    .write_to(&out)?;

  // src/lib.rs: real path, so IDE go-to-definition works
  #[allow(dead_code, unused_imports, non_camel_case_types, non_snake_case, clippy::all, warnings)]
  #[path = "generated/messages.rs"]
  mod messages;

Buffer sizing guide

The rule table is Buffer sizing: compute_length_with_header for a fixed message, the staged *EncodedLength builder when the message has groups or var-data, and no guessed buffer.

A fixed message is a stack array of the length that page names:

#![allow(unused)]
fn main() {
  let mut buf = [0u8; HeartbeatEncoder::compute_length_with_header()];
}

Inspect bytes with no codec

ergo-sbe-inspect reads SBE bytes at run time. Load any number of schemas; give it bytes; it says which message of which schema the bytes most likely hold, how sure that is, and prints them. Nothing is generated or compiled: it walks the token IR that ergo-sbe parses, so any schema ergo-sbe accepts can be read.

Use it to look at a recording, a capture or a log line without knowing in advance which schema, message or framing it uses. For a codec you compile in, the generated decoder’s Display is faster (Display and Debug).

It is the crate ergo-sbe-inspect (sbe/inspect):

ergo-sbe-inspect = { version = "0.1", default-features = false }  # the library
FeatureDefaultAdds
cliyesthe sbe-inspect filter
httpnoschemas from HTTPS URLs

AI assistance: like the rest of ergon, this crate was written with heavy AI assistance (disclosure). It is not production-ready.

In four calls

StepCallFails with
Load schemasCatalogue::builder().path("schemas/")?.xml("name", xml)?.build()?CatalogueError
Make an inspectorInspector::new(&catalogue)never
Read bytesinspector.inspect(bytes) returns a Readingnever: unknown bytes are a reading
Printreading.compact(), .pretty() or .json() (each Display)never

All four, reading a capture file with a schema file or directory (the example is compiled with the crate; cargo run -p ergo-sbe-inspect --example read_capture -- <schemas> <capture>):

fn main() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = std::env::args().collect();
    let (schemas, capture) = (
        args.get(1).ok_or("schema path")?,
        args.get(2).ok_or("capture path")?,
    );
    let catalogue = Catalogue::builder().path(schemas)?.build()?;
    let bytes = std::fs::read(capture)?;
    print!("{}", Inspector::new(&catalogue).inspect(&bytes).pretty());
    Ok(())
}

On the car schema and the car capture the tests write, it prints the pretty output shown under The three outputs. The crate documentation’s example does the same on an inline schema and is compiled and run as a doctest.

Loading schemas

SourceCallA file that is not an SBE schema
One file.path("car.xml")fails the load, naming the file
A directory.path("schemas/"): every *.xml, sorted, at most 16 levels deepis skipped and listed in Catalogue::skipped()
Inline XML.xml("name", text)fails the load, naming name

CatalogueError has four cases: Io (a path cannot be read), Schema (ergo-sbe rejected it, with its parser error), Unsupported (it parsed but the walker cannot use it, for example groups or composites nested deeper than 32 levels) and Empty (nothing loaded). Two schemas with the same id are both kept; a reading that cannot choose between them lists both.

What a reading can be

ReadingMeaning
MessageAn SBE message of a loaded schema: its match class, fields, evidence and length
TextValid UTF-8 whose characters are printable, tab, newline or carriage return
FramedRecords a framing cut out of the bytes (Framing detection)
AmbiguousSeveral readings equal on every ranking rule, each with its evidence
PaddingAll zero bytes
UnknownBytes nothing explains, shown in full

A var-data field with no characterEncoding is read again as bytes of its own, so a message inside a message is decoded too, up to a depth limit. The bytes after a message are read again the same way.

Match classes

Every message is printed with its match class first, so a guess never looks like a fact.

ClassWhenHow far to trust it
ExactThe header’s schemaId and templateId are both in the catalogueThe identity is certain; the values are what the bytes say
TemplateOnlyThe templateId exists in a loaded schema with another idA schema-id mismatch: the right layout, the wrong schema, or chance
InferredNo usable header: the bytes were read as a bare message bodyA guess: kept only when it uses every byte and nothing counts against it

A car message with its 8-byte header removed reads as Inferred:

Inferred Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }

A message cut short is still shown, with the rule that stopped the walk (hard rules), and the bytes after the cut follow it as unknown bytes, so none is dropped. The car message cut to 60 bytes: its fuelFigures group declares 2 entries that no longer fit:

Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [(0 of 2 read)] } truncated at 53 (H4)
Unknown(7) 0x1e009a990f423c

The three outputs

compact is one line per message, in the generated decoder’s Display style:

Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }

pretty is for people: the match class, schema, wire version, length and evidence first, then one field per line:

Car  Exact  schema 1 v1 (uk.co.real_logic.sbe.benchmarks)  template 1  wire v1 blockLength 41  108 bytes  complete  evidence: +enums valid, +chars printable, +text valid, +header ids found, +version equal, +ends exactly
  serialNumber: 1234
  modelYear: 2013
  available: T
  code: A
  someNumbers: [10, 20, 30, 40, 50]
  vehicleCode: "ABCDEF"
  extras: sportsPack|cruiseControl
  engine:
    capacity: 2000
    numCylinders: 4
    maxRpm: 9000
    manufacturerCode: "123"
    fuel: "Petrol"
  fuelFigures: 2 entries
    [0]
      speed: 30
      mpg: 35.9
    [1]
      speed: 60
      mpg: 25.0
  performanceFigures: 1 entries
    [0]
      octaneRating: 95
      acceleration: 2 entries
        [0]
          mph: 30
          seconds: 4.0
        [1]
          mph: 60
          seconds: 7.5
  manufacturer: "Honda"
  model: "Civic VTi"

json is one object per record per line, for other programs:

{"type":"message","class":"Exact","message":"Car","schema":{"package":"uk.co.real_logic.sbe.benchmarks","id":1,"version":1},"template":1,"header":{"blockLength":41,"templateId":1,"schemaId":1,"version":1},"actingVersion":1,"actingBlockLength":41,"consumed":108,"complete":true,"truncated":null,"evidence":[{"kind":"enums valid","against":false,"at":""},{"kind":"chars printable","against":false,"at":""},{"kind":"text valid","against":false,"at":""},{"kind":"header ids found","against":false,"at":""},{"kind":"version equal","against":false,"at":""},{"kind":"ends exactly","against":false,"at":""}],"fields":{"serialNumber":1234,"modelYear":2013,"available":"T","code":"A","someNumbers":[10,20,30,40,50],"vehicleCode":"ABCDEF","extras":["sportsPack","cruiseControl"],"engine":{"capacity":2000,"numCylinders":4,"maxRpm":9000,"manufacturerCode":"123","fuel":"Petrol"},"fuelFigures":[{"speed":30,"mpg":35.9},{"speed":60,"mpg":25.0}],"performanceFigures":[{"octaneRating":95,"acceleration":[{"mph":30,"seconds":4.0},{"mph":60,"seconds":7.5}]}],"manufacturer":"Honda","model":"Civic VTi"},"trailing":null}

A single char field prints in json as a string of one char, a zero byte as "\u0000"; as in JsonPrinter, a byte above 0x7f is sign-extended (0xe9 is U+FFE9). A constant prints as a number, or as a string for char; a constant enum field as the value’s name alone ("C"); a valueRef on a number or char field as the value it refers to. fields is shaped as the output of sbe-tool’s JsonPrinter, and differs from it on purpose here:

ValueJsonPrinterjson
A set{ "sportsPack": true, "sunRoof": false }["sportsPack"]: the bits set
An optional field holding nullthe type’s raw null valuenull
A field newer than the writer’s versionthe type’s raw null value{"absent":true}
A constant newer than the writer’s versionits value{"absent":true}
Binary var data"ff007f""0xff007f": not a string of text
A uint64 above i64::MAXa negative numberthe unsigned number
A float constant such as 0.1its digits as a double: 0.100000001490116120.1
A constant that is not finite"0/0", "1/0", "-1/0""NaN", "inf", "-inf"; a -NaN as its bits ("NaN(0xffc00000)" for a float)

compact prints every field the generated Display prints, with the same name and value text, and more: the fields Display skips (constants such as maxRpm, and fixed arrays such as someNumbers), and the raw value wherever Display would lose it. It differs on purpose in a few places:

ValueGenerated Displaycompact
A composite or group entryEngine { .. }, FuelFiguresEntryDecoder { .. }{ .. }
Binary var data that is not UTF-8"<3 bytes>"0xff007f
An enum value the schema does not defineNullValinvalid(7)
Set bits the schema does not definedroppedbit9
An optional field holding nullNonenull
A field newer than the writer’s versionNoneabsent
A NaN other than the canonical quiet one (a payload, or the sign set)NaNNaN(0x7fc00001): its bits
A group the walk stopped inside(not printed)[(0 of 2 read)]: entries read, of the count on the wire
A group or var data whose prefix does not fit(not printed)cut

Every printed string is escaped (Rust Debug escaping in compact and pretty, JSON escaping of every control character in json), payload text and schema text (names, the package, constants) alike, so neither a payload nor a schema can send control characters to a terminal.

Next

The sbe-inspect filter

sbe-inspect decodes the SBE messages in its input with the schemas named on its command line, and passes through, byte for byte, whatever it cannot decode. It is ergo-sbe-inspect as a pipe filter, in the manner of c++filt: put it in any pipeline and only what it recognises changes.

Install it (Rust 1.99 or newer):

cargo install ergo-sbe-inspect                   # schema files and directories
cargo install ergo-sbe-inspect --features http   # also https:// schema URLs
cargo install --path sbe/inspect                 # from a checkout of the repository

The http feature uses the platform’s TLS and certificate store; on Linux it needs the OpenSSL headers to build.

usage: sbe-inspect [SCHEMA_FILE|DIR|URL]... [OPTIONS] < INPUT

Decodes the SBE messages on stdin with the given schemas (files, directories
walked for *.xml, and https:// URLs). Input it cannot decode is written
unchanged when stdout is not a terminal, and shown as text or hex on one.

options:
  --format pretty|compact|json  how a decoded message is printed (default:
                                pretty on a terminal, compact otherwise)
  --input auto|bin|lines        auto (default): lines when the input's first
                                line is text, else bin
  --framing auto|NAME           fix the framing of bin input and of decoded
                                runs, by the name it is printed with, e.g.
                                'aeron-frame', 'back-to-back', 'sofh big-endian',
                                'length-prefix u32 little-endian payload-only',
                                'skip-then 10 + single'
  --strict                      exit 1 when any input was not recognised
  --max-buffer BYTES            most bytes held for an incomplete record
                                (default 4194304)
  --allow-http                  fetch http:// schema URLs too (http feature)
  --offline                     read schema URLs from the cache only (http
                                feature)
  -h, --help                    print this text

exit status: 0 done, even when nothing decoded; 1 with --strict when some input
was not recognised; 2 bad arguments, a schema that does not load, or an I/O
error.

Binary input

A capture of length-prefixed records, two car messages around a record that is not SBE, decoded with the car schema. The passthrough bytes include NULs, so the output goes through cat -v:

sbe-inspect sbe/tests/fixtures/schemas/car.xml --format compact \
  < sbe/inspect/tests/book/filter-capture.bin | cat -v
Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
^R^@^@^@not an SBE messageExact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }

The framing (a little-endian u32 length before each record) was detected and each car printed on its own line. The middle record, its length (^R^@^@^@, 18) and its 18 bytes, came out exactly as it went in, so the second car’s line starts straight after it. Nothing is dropped and nothing is changed: input with no SBE in it comes out identical, which the tests check byte for byte.

InputWritten to a pipe or fileShown on a terminal
Recognised: an Exact, complete message (or a run of them) that explains every byte of its record, and whose decoded text shows every byte the walk readThe decoded text in --formatThe same
Anything else: TemplateOnly and Inferred guesses, text, unknown bytes, a record cut short, a message whose block holds bytes no decoded field shows (a writer whose block is longer than the schema’s, or an older writer with bytes under fields newer than its version, zeros included)The input bytes, unchangedThe reading: labelled guesses, text or hex, every control character escaped

--format defaults to pretty on a terminal and compact elsewhere; json writes one object per message. Zero padding counts as recognised, and is printed as Padding(n), only where the framing explains it: between two recognised records, or after a recognised message in Aeron frames (the term’s unwritten tail, however long). Zeros anywhere else, such as after a single message or among unknown bytes, come out unchanged. Zero-filled Aeron padding frames and alignment are framing, like a length prefix, and print nothing; Aeron alignment bytes or padding-frame bodies that are not zero come out unchanged.

“Every byte the walk read” has two exceptions, both the format rather than data: the message header’s four standard fields, which compact reduces to the message name and match class (pretty and json print them), and padding the schema itself declares (a gap left by explicit offsets, or a blockLength longer than the fields), which the generated decoders do not show either. A header or group dimension with any other member (an SBE 2.0 numGroups, say) is read but shown by no output, so such a message passes through unchanged.

--framing fixes the framing instead of detecting it, by the name the framing is printed with (Framing detection): --framing aeron-frame for a term buffer or an archive segment, --framing 'length-prefix u32 little-endian payload-only' for the capture above.

Streaming

The filter reads its input as it arrives and flushes whenever it writes:

  • A recognised record is written as soon as it is complete.

  • An incomplete record waits for more input; at the end of the input it is written as it stands.

  • In a framing whose own structure marks every record (a length prefix, a SOFH, Aeron frames, a skipped header before one of those), a record that is not recognised is written once a later record is. Bytes only content marks (scan, back-to-back, a single payload) wait for the end of the input.

  • So the output mostly does not depend on how the input arrived in reads: the tests cut streams in every framing at every byte and compare. Known exceptions, where a prefix is explained by a framing that the whole input is not, so the whole input is scanned instead:

    • a skipped leading header followed by a record that is not SBE;
    • length-prefixed records followed by zeros;
    • Aeron frames followed by zeros and then bytes that are not zero (with --framing aeron-frame, the whole input is then not recognised at all).

    The same messages are decoded either way; what differs is whether the framing bytes (length prefixes, frame headers) come out raw or hidden, and whether the zeros print as Padding(n).

  • Nothing waits beyond --max-buffer bytes (4 MiB by default): past it, what is held is written as it stands. Such a flush can write raw what a larger buffer would decode (a record longer than the buffer, zeros between two recognised records). The one case the other way: zeros after Aeron frames are printed as the term’s tail up to the flush, even if bytes that are not zero follow later, which a larger buffer would write raw. With a small buffer, where the reads fall can also decide whether a message held at a flush is decoded or written raw, and where the Padding(n) lines of a long Aeron tail break.

Log lines

With --input lines, or by default when the input’s first line (within its first 4 KiB) is text with at least one character that is not white space, the filter reads lines; the choice is made on that line alone. So binary input whose first byte is a newline (a length of 10) stays binary; one whose first bytes happen to be printable characters and a newline (a little-endian length such as 0x0A41 or 0x0A4141) reads as log lines, unless --input bin is given. Each run of hex digits (optionally after 0x) or of standard base64 that decodes to a recognised message is replaced in place; the rest of the line, and every run that does not decode, stays byte for byte as it was. A log with the car message as hex and as base64:

12:00:01.481 INFO  gateway rx len=108 payload=2900010001000100d2040000dd0701410a000000140000001e000000280000003200000041424344454606d00704313233060002001e009a990f423c000000c841010001005f060002001e00000080403c000000f04005000000486f6e646109000000436976696320565469
12:00:01.502 INFO  gateway rx payload_b64=KQABAAEAAQDSBAAA3QcBQQoAAAAUAAAAHgAAACgAAAAyAAAAQUJDREVGBtAHBDEyMwYAAgAeAJqZD0I8AAAAyEEBAAEAXwYAAgAeAAAAgEA8AAAA8EAFAAAASG9uZGEJAAAAQ2l2aWMgVlRp
12:00:01.503 WARN  gateway slow consumer, 3 messages behind
sbe-inspect sbe/tests/fixtures/schemas/car.xml < sbe/inspect/tests/book/filter-log.txt
12:00:01.481 INFO  gateway rx len=108 payload=Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
12:00:01.502 INFO  gateway rx payload_b64=Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
12:00:01.503 WARN  gateway slow consumer, 3 messages behind

A decoded run stays on its line: pretty is written as compact, json as one line, and several messages in one run are joined by |. A run must decode to at least 8 bytes, one message header, and every byte of it must be recognised: a run holding a message and zeros before or after it stays as it is. Line endings, a missing last newline and bytes that are not UTF-8 are kept; on a terminal, control characters in the line are escaped too. A text with no message in it comes out unchanged: the tests run the repository’s changelog through every fixture schema.

Exit status and --strict

ExitWhen
0Done, even when nothing was decoded; also when the reader closes the pipe (| head)
1--strict, and some input was not recognised: bytes in binary input, lines with nothing decoded in log lines
2Bad arguments, a schema that does not load, or an I/O error

Diagnostics go to standard error only: files skipped in a schema directory, and the count --strict found. On the capture above, --strict exits 1 and writes:

sbe-inspect sbe/tests/fixtures/schemas/car.xml --strict \
  < sbe/inspect/tests/book/filter-capture.bin > /dev/null
sbe-inspect: --strict: 22 bytes not recognised

The 22 bytes are the middle record and its length.

Schemas from a URL

With the http feature, a schema argument may be an https:// URL. Schemas are fetched before any input is read, never while decoding.

RuleDetail
HTTPS onlyAn http:// URL, or a redirect to one, is refused unless --allow-http is given; that holds for the cache too
SizeAt most 4 MiB
Time10 s for the whole request, redirects included
RedirectsAt most 3
Self-containedA schema that includes other files is refused: an include would be read from this machine
DTDsRefused by the XML parser, so an entity bomb fails cleanly
CacheOne file per URL (a hash, with the URL beside it to rule out a collision) under $XDG_CACHE_HOME/sbe-inspect, else ~/.cache/sbe-inspect; read back with the same checks
Offline--offline reads the cache only and never connects
CertificatesThe platform’s store: Security.framework on macOS, OpenSSL’s default paths on Linux, SChannel on Windows
sbe-inspect https://<host>/schemas/car.xml < capture.bin

From a program

The filter is ergo_sbe_inspect::filter::run over any reader and writer, with the same options; CatalogueBuilder::url fetches a schema with the limits of a Fetch.

Next

How a reading is chosen

The inspector has no weights and no confidence number. It tries candidates, counts named evidence, and compares candidates in a fixed order; the first difference decides. This page is that order.

  1. All zeros (not empty)? Padding; empty: Unknown
  2. Header candidates. For each schema, read its own header layout. Both ids found: Exact; only the template id: TemplateOnly. Walk each one; a broken hard rule (H1 to H5) ends it, marked truncated. Each walk is one unit of the work budget.
  3. An Exact, complete candidate? Yes: go to 6.
  4. Printable UTF-8? Text
  5. No header candidate complete? Read the bytes as every message's bare body; keep those that use every byte with no evidence against: Inferred.
  6. Rank: match class, complete, bytes consumed, evidence against, version distance. One best: Message; a tie: Ambiguous; none: Unknown. If the work budget ran out while the candidates were read, the payload is Unknown, marked with the work limit, never a ranking of a subset.
  7. Retry. Bytes left after a complete message are read again as records one after another (after a truncated one they are kept as unknown bytes); var data with no characterEncoding is read again one level deeper, up to the depth limit.

Candidates

A candidate is “these bytes are message M of schema S, starting at the first byte”. Each loaded schema reads the header with its own header composite (headerType, any offsets and widths, the schema’s byte order). When the header’s templateId is a message of that schema, the candidate is walked: header, root block, groups (nested), var data, in wire order.

Versioning follows the generated decoders. The acting block length is the wire blockLength; a field whose sinceVersion is above the wire version, or that lies past the acting block length, is absent; bytes of a root block or group entry that no field shows are skipped, with a note: bytes past the schema’s block (a newer writer’s fields, or bytes no version explains), and an older writer’s bytes under fields newer than its version.

Hard rules

Breaking one ends the walk at that offset. What was read so far is kept, the message is marked truncated with the rule, the group or var data it stopped at prints as cut (or as the entries read, of the count on the wire), and the bytes after the cut follow as unknown bytes.

RuleCheck
H1The header fits in the bytes
H2The wire blockLength fits in the remaining bytes
H3When the wire version is at or above the schema’s, the wire blockLength is at least the schema’s block length
H4Each group dimension fits, numInGroup times its blockLength fits, and each entry’s block fits where the entry starts
H5Each var-data length prefix fits, and so do its bytes
H6A group whose entries take no bytes is walked once, never numInGroup times: one entry stands for all of them

Evidence

Evidence is counted and shown, never fatal. pretty prints evidence for with + and against with -, with the field it concerns.

AgainstFor
An enum value that is neither a valid value nor nullEvery enum holds a valid value or null
A set bit the schema does not defineEvery char field is printable, or zero-padded
A value outside a declared minValue/maxValue (a var-data length too)Every var data with a characterEncoding is valid in it
A char field with unprintable bytesThe header’s schemaId and templateId were both found
Var data invalid in its declared characterEncodingThe wire version equals the schema version
At the schema’s version, a wire blockLength that differs from the schema’sThe message ends exactly at the end of the bytes
Bytes left after the messageA note, not a vote: block bytes no field shows (past the schema’s fields, or under fields newer than the wire version), skipped

Text in a known encoding (UTF-8, ASCII, ISO-8859-1) is decoded; text invalid in its encoding is shown as bytes, never repaired. Text in an encoding the inspector does not decode is shown as bytes too, and never read again as SBE.

The comparison order

OrderEvidenceBetter is
1Match classExact, then TemplateOnly, then Inferred
2The walk broke no hard rulecomplete
3Bytes consumedmore
4Evidence againstfewer
5Version distanceequal, then an older writer, then a newer one
  • Candidates equal on all five are Ambiguous, every one listed with its evidence (at most Limits::max_candidates, then a count of the rest).
  • Text loses to an Exact, complete message and beats every other candidate. All-zero bytes are Padding.
  • Inferred bodies are tried only when no header-based candidate completes, and one is kept only when it uses every byte and has no evidence against. A message of plain integers fits any bytes of its length, so every survivor is listed.
  • Nothing left: Unknown, the bytes in full.

Limits and untrusted input

Schemas and payloads are both untrusted. For any bytes and any schema that parses, inspect does not panic, does not loop without bound and returns a reading.

Limits fieldDefaultPast it
max_depth8var data deeper than this is Unknown, marked with the depth limit
max_input16 MiBthe whole input is Unknown, marked with the input-size limit
max_candidates8an Ambiguous lists this many and counts the rest
max_walks20 000nothing more is walked; what is left is Unknown, marked with the work limit
max_skip64the longest leading header skip-then tries (framing)

The work budget is one unit per candidate walk, plus one per 64 group entries walked (ENTRIES_PER_UNIT) and one per 64 KiB of a long text check, across framings, retries and scans, so one walk over a long buffer is paid for too. When the budget runs out while a payload’s candidates are being read, the whole payload is Unknown, marked with the work limit: a ranking over only the candidates read so far could be a confident wrong answer. Inspector::work() reports the count and every limit hit. At load, groups and composites nested deeper than 32 levels are refused. A schema with a DTD (and so any entity-expansion bomb) is refused by the XML parser before ergo-sbe reads it. A fuzz target, inspect_bytes in sbe/fuzz, drives schemas and bytes together.

Framing detection

A buffer may hold one message, many, or messages inside a transport’s frames. A framing is a rule that cuts the buffer into records; each record is then read as on How a reading is chosen.

The framing that won last time→explains every byte?→yes: keep it, try nothing else
no, or none learnt yet: score every framing, in table order
singleback-to-backlength-prefix ×8sofh ×2aeron-frame
only while the best still leaves bytes unexplained, and no container framing tiles the whole buffer with an Exact message:skip-then 1 to 64 bytesscan
Score: more bytes in Exact, complete messages; then fewer unexplained bytes; then fewer records with evidence against; then the earlier row→one best: its records; a tie: Ambiguous

The framings

FramingRule
singleThe whole buffer is one payload. Bytes after a message are read again as a nested reading
back-to-backMessages with headers, one after another; each length comes from its own walk. What follows the last message is one final record
length-prefixA 2- or 4-byte length, little- or big-endian, counting the payload alone or the payload plus the prefix (8 variants). The chain must land on the end of the buffer, except an incomplete last record, which is held as pending. A zero length ends the chain as a non-match
sofhFIX Simple Open Framing Header: a 4-byte length that counts the 6-byte header too, then a 2-byte encoding type, which must be SBE 1.0 (0x5BE0 big-endian or 0xEB50 little-endian). The header is big-endian by default; little-endian is tried too, as the standard allows by agreement
aeron-frameAeron data frames as in a term buffer or an archive segment: a 32-byte little-endian header (frame_length first), frames aligned to 32 bytes, padding frames skipped (one whose body is not zeros is an unknown record), alignment bytes that are not zero an unknown record, a zero length ending the written part (the rest must be zeros, shown as a padding record, or pending with a message still being reassembled)
skip-thenA leading header of 1 to 64 bytes (Limits::max_skip), then one of the framings above covering the rest exactly: real messages and no unexplained bytes
scanThe last resort: slide forward to each offset where an Exact, complete message starts; the gaps are shown as text, padding or unknown bytes

A caller that knows the framing fixes it with Inspector::with_framing and skips detection.

Choosing a framing

Each framing that fits the bytes is scored, and the first difference decides:

OrderBetter is
1more bytes inside Exact, complete messages
2fewer bytes nothing explains
3fewer records with evidence against
4the earlier row in the table above

Rows 1 and 4 mean a run of messages is back-to-back rather than single (the messages found by reading a single message’s trailing bytes again do not count in row 1), and one message alone is single. A tie inside one row, such as two length-prefix variants landing on the same records, is Ambiguous, both splits shown.

skip-then and scan always leave some bytes unexplained (the skipped header, the gaps), so they are tried only while the best framing so far does too, and never when a container framing (length-prefix, sofh or aeron-frame) holds together over the whole buffer: its records tile every byte (on a stream prefix, a held last record aside) and it holds at least one Exact, complete message. scan takes any Exact, complete message it can find, and a message header followed by zeros reads as one with empty groups and empty var data; this rule stops such a chance match, inside an Aeron frame’s header and alignment padding, from outscoring the frame chain that shows a broken fragment honestly as unknown bytes.

Learning across buffers

An Inspector keeps the framing that won the last buffer. On the next buffer it tries that framing first; if it explains every byte, it is kept and no other framing is tried. Otherwise every framing is tried again. There are no counters and no thresholds. Inspector::learnt_framing shows it.

Incomplete records

On a buffer cut from a stream, the last record may be incomplete: a length-prefix or SOFH length that runs past the end, an Aeron frame still being written (Aeron negates the length until the frame is done), or a fragmented message whose last fragment has not arrived. Those bytes are kept as pending and printed after the records (Pending(12) 0x..). By default they count as unexplained, so stray bytes after a framing’s last record can never hide there. An inspector made with with_stream_prefix(true) reads each buffer as the start of a stream that goes on: there the pending bytes wait for more input and do not count against the framing, once it holds at least one Exact, complete message. On such a buffer an Aeron frame whose 32-byte alignment padding has not arrived yet is pending too, so the padding is never read as the start of the next frame.

Each record also gives its raw position: start is its first byte, framing header included, and the records’ starts with pending_at (where the pending bytes start) cut the buffer into contiguous spans, so a caller can copy any record’s bytes unchanged. The sbe-inspect filter passes unrecognised records through this way.

Fragmented Aeron messages

Aeron splits a message larger than one frame into fragments, marked with the BEGIN (0x80) and END (0x40) flags. The inspector reassembles them before decoding, as Aeron’s fragment assembler does: each fragment must start at the term offset where the one before ended. A fragment that does not continue the message, and a message whose END never comes before another BEGIN, are shown as unknown bytes, never dropped. A reassembled record says how many fragments it came from.

A term with a whole car message, then an Aeron cluster SessionEvent split into two fragments, then unwritten zeros:

framing: aeron-frame, 3 records
record 0 at 32, 108 bytes:
  Car  Exact  schema 1 v1 (uk.co.real_logic.sbe.benchmarks)  template 1  wire v1 blockLength 41  108 bytes  complete  evidence: +enums valid, +chars printable, +text valid, +header ids found, +version equal, +ends exactly
    serialNumber: 1234
    modelYear: 2013
    available: T
    code: A
    someNumbers: [10, 20, 30, 40, 50]
    vehicleCode: "ABCDEF"
    extras: sportsPack|cruiseControl
    engine:
      capacity: 2000
      numCylinders: 4
      maxRpm: 9000
      manufacturerCode: "123"
      fuel: "Petrol"
    fuelFigures: 2 entries
      [0]
        speed: 30
        mpg: 35.9
      [1]
        speed: 60
        mpg: 25.0
    performanceFigures: 1 entries
      [0]
        octaneRating: 95
        acceleration: 2 entries
          [0]
            mph: 30
            seconds: 4.0
          [1]
            mph: 60
            seconds: 7.5
    manufacturer: "Honda"
    model: "Civic VTi"
record 1 at 192, 61 bytes, 2 fragments:
  SessionEvent  Exact  schema 111 v18 (io.aeron.cluster.codecs)  template 2  wire v18 blockLength 44  61 bytes  complete  evidence: +enums valid, +text valid, +header ids found, +version equal, +ends exactly
    clusterSessionId: 77
    correlationId: -1
    leadershipTermId: 3
    leaderMemberId: 2
    code: REDIRECT
    version: 66051
    leaderHeartbeatTimeoutNs: null
    detail: "moved"
record 2 at 288, 64 bytes:
  Padding, 64 bytes

The same term in compact, one line per record:

Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
Exact SessionEvent { clusterSessionId: 77, correlationId: -1, leadershipTermId: 3, leaderMemberId: 2, code: REDIRECT, version: 66051, leaderHeartbeatTimeoutNs: null, detail: "moved" }
Padding(64)

ergo-aeron

ergo-aeron shows what an Aeron media driver is doing: every counter with its rate, one row per stream with every position and which subscriber holds the publisher back, the error log, the loss report, the driver’s own metadata, and one stream’s messages decoded with your SBE schemas. It reads the driver’s cnc.dat and loss-report.dat and, for messages, the stream’s log file. For these tabs it starts no Aeron client and adds no subscription, so the driver and its publishers cannot tell it is there (the archive tabs’ --control session is a client: Archive tabs). That is attached mode, the default; with --embedded it runs a driver of its own and can join a stream named by its channel as a guarded receiver instead (Attached or embedded).

Install

It is the crate ergo-aeron-tools. Aeron’s C is built from source: the build needs CMake, a C compiler and libclang (on Linux also the uuid and libbsd development packages), and, for the archive client’s codecs, a JDK 17 or newer with network access the first time (Aeron’s Gradle).

cargo install ergo-aeron-tools
# No JDK: no `recordings`, `recording`, `replay` or `--control`.
cargo install ergo-aeron-tools --no-default-features --features cli,tui,static
# From a checkout of the repository:
cargo install --path aeron-tools

Without archive (--no-default-features --features cli,tui,static), recordings, recording, replay and --control are not there (Archive tabs).

Then, where the driver’s directory is visible:

ergo-aeron --aeron-dir /dev/shm/aeron
FeatureDefaultAdds
cli, tuiyesthe subcommands and the terminal UI
staticyesAeron linked into the binary, so it runs from wherever it is copied. Without it the program needs libaeron on the loader path, so keep it for an installed binary
archiveyesthe archive control reader (Archive tabs); the one part that needs a JDK
httpno--schema https://...

With no subcommand on a terminal it opens the screen below. With a subcommand it prints and exits, so every tab also works in a pipe (In scripts and pipes). --aeron-dir defaults to AERON_DIR, then to Aeron’s own default directory.

In a checkout of the repository, just run-sample starts a driver with live SBE publishers and consumers and opens ergo-aeron on them (CMake and a C compiler); just run-sample archive adds a Java Aeron Archive recording the streams (also JDK 17 or newer). Streams and keys: samples/README.md. For a driver in a cluster, see In Kubernetes.

To see a driver with trouble in it, start the example driver: one IPC stream (1001) whose only subscriber never polls, so its publisher sits at its limit, one (1002) carrying a car-schema message every 20 ms, and one refused endpoint in the error log. Ctrl-C stops it and removes its directory.

cargo run -p ergo-aeron-tools --example fixture_driver -- target/fixture-aeron
cargo run -p ergo-aeron-tools --bin ergo-aeron -- --aeron-dir target/fixture-aeron \
    --schema sbe/tests/fixtures/schemas/car.xml

The Messages tab is Live messages. With --control URI or --archive-dir DIR the screen gains an Aeron Archive’s tabs, Recordings, Payload and Archive dir (Archive tabs); --archive-dir alone opens with no driver, and an archive seen in the driver’s counters adds the Recordings tab by itself.

The screen

ergo-aeron  [READ ONLY]  dir=/dev/shm/aeron-test  driver pid 4121  heartbeat 3 ms
ALARM  Sender flow control limits, i.e. back-pressure events: rose by 3 to 3
 Counters   Streams   Errors   Loss   Driver   Messages
? help   / filter   Space pause   m mark   s sort   q quit
stream   session   pub pos   pub limit   snd pos   snd limit   rcv hwm   rcv pos   subscribers (id@pos)   slowest   behind   headroom %   channel
1001     77        97920     98304       -         -           -         -         7@65536 9@97920        7         32384    1.2          aeron:ipc?term-length=65536
2002     5         1048576   1179648     1046528   1179648     -         -         13@1040384             13        8192     94.1         aeron:udp?endpoint=10.0.0.1:40123

The top line says the tool is read-only, or [WRITE] when started with --write (the one write action) (and, in embedded mode, [LIVE RECEIVER]), then the directory, the driver’s pid and the age of its heartbeat. The second line is the health verdict (OK, WARN or ALARM) with its first reason; Driver tabs and Aeron’s own tools lists what it watches. Then the tabs, then the filter line, then the list.

TabSubcommandAeron 1.54.3 toolShows
CounterscountersAeronStatevery counter: value, change per second, change since the mark
StreamsstreamsStreamStat, BacklogStatone row per stream: every position, backlog, the slowest subscriber and the publisher’s headroom
ErrorserrorsErrorStatdistinct errors with their count, first and last time
LosslossLossStatper stream: gaps and bytes lost
DriverdriverDriverTool (pid, CnC metadata)pid, versions, buffer lengths, heartbeat age
Messagesmessagesnone (LogInspector reads the same log file, offline)one stream’s messages, read from its log file with no subscription, decoded with the schemas given; counts per message type
Recordingsrecordingsnone (the archive client’s listRecordings and position queries)an archive’s recordings from its control session, read requests only: positions, start and stop, stream, channel, session; each active recording’s lag
Payloadreplaynone (the archive client’s startReplay)one recording’s messages, replayed through the control session and decoded with the schemas given; live while it records
Archive dirarchive-dirArchiveTool (describe, describe-all, count-entries, capacity, pid, errors, dump, verify without marking)an archive directory read as files, never written: catalogue, mark file, segment files, disk use and time until full

Keys and mouse

Every action has a vim key and a plain key:

ActionVimPlain
move upkUp
move downjDown
half a page upCtrl-uPageUp
half a page downCtrl-dPageDown
first rowggHome
last rowGEnd
next tabgtTab
previous tabgTShift-Tab
open the selected row’s detail (Messages: the message’s preview)lEnter Right
show the selected stream’s (or recording’s) messageswF4
Messages tab: hide or show what the values mean (shown at start)ii
Counters: mark the next link in the detail (owner, stream, …)rF8
Counters: jump to the marked link, on the tab and row it namesfF9
Counters: scroll the open detail down]F10
Counters: scroll the open detail up[F11
close the detail, the filter or help; quit at the topqEsc
close the detail, the filter or help; never quitshLeft
filter the list; search the preview (regex); capitals: exact case/Ctrl-f
next matching row (in a preview: next match)nF3
previous matching row (in a preview: previous match)NShift-F3
pause or resume the live viewSpaceSpace
mark: count counters from now (C2)mF5
sort by the next column (again: reverse, then off)sF6
open a stream, channel or schema used before (history)oF7
connect to the archive seen in the counters (again: other channel)cF12
–write: this tab’s write actionsaF2
Messages: the open preview full screen, lines wrapped (again: back)zz
Messages: copy the open preview to the clipboard (OSC 52)yy
mouse capture off, so the terminal selects text (again: on)MM
help?F1

/ opens the filter: a regular expression over the whole row (bytes rec or bytes.*received finds Bytes received); a query with no capital ignores case. A pattern that is not one yet, half typed, is matched as written, and the filter line says so. The list keeps its order, and the matched text is highlighted. Enter keeps the filter, Esc drops it.

The mouse does the same: click a tab, a row or a column header (again to reverse, a third time to unsort), and the wheel scrolls. M turns mouse capture off so the terminal can select text (Copy and select). The selection stays on the same counter or stream while the values change and the rows move.

Space pauses the tables; the health line stays live. m marks: the since mark column counts from that moment, and the health line forgets warnings older than the mark, which is how to watch a test run from a clean start. Enter opens the selected row’s detail; on the Streams tab it starts with the main fields of the stream’s log (log inspector). On the Counters tab a sparkline under the list shows the selected counter’s change per read. On the Streams tab w shows the selected stream’s messages (on the Recordings tab it replays the selected recording), and o (or F7) opens the history of streams, channels and schemas used before (history).

Live messages

The Messages tab shows one stream’s messages as they are published, decoded with the SBE schemas you give, with no codec compiled for them. It reads the stream’s log file and never subscribes, so the publisher cannot be slowed by it (why). Embedded mode is the exception: it joins a stream named by its channel as a guarded receiver (Attached or embedded). Decoding is ergo-sbe-inspect: each message is read as one payload, and its match class (Exact, TemplateOnly, Inferred) says how sure the reading is.

ergo-aeron is the installed binary (Install).

Choosing a stream and schemas

--schema names a schema file, a directory of *.xml files, or (feature http) an HTTPS URL; repeat it for more. Schemas load before the screen opens. Without one, messages are shown as bytes.

ergo-aeron --aeron-dir /dev/shm/aeron --schema schemas/ --stream 1001

--stream N (and --session S when the stream has several sessions) opens the screen on that stream’s Messages tab. Or pick one on the Streams tab: select its row and press w (or F4). A publication on this driver is read in preference to an image of the same session. The tab starts with what the driver still keeps of the stream, then follows it.

The example driver of the overview carries a car-schema message every 20 ms on stream 1002:

cargo run -p ergo-aeron-tools --example fixture_driver -- target/fixture-aeron
ergo-aeron --aeron-dir target/fixture-aeron --schema sbe/tests/fixtures/schemas/car.xml --stream 1002

The screen

ergo-aeron  [READ ONLY]  dir=/dev/shm/aeron-test  driver pid 4121  heartbeat 3 ms
OK
 Counters   Streams   Errors   Loss   Driver   Messages
? help   / filter   Space pause   m mark   s sort   q quit
stream 1001 session 77 aeron:ipc?term-length=65536 (publication)  4 read  skipped 0 bytes  dropped 0  interpret
position   seen (UTC)             bytes   class   message   decoded                │ preview: match 1 of 2 (n, N)
0          2025-11-29 07:06:40.25 108     Exact   Car       Exact Car { serialNumbe│      speed: 30
160        2025-11-29 07:06:40.25 4       Unknown ?         Unknown(4) 0xcafe0001  │      mpg: 35.9
320        2025-11-29 07:06:40.25 108     Exact   Car       Exact Car { serialNumbe│    [1]
480        2025-11-29 07:06:40.25 108     Exact   Car       Exact Car { serialNumbe│      speed: 60
                                                                                   │      mpg: 25.0
                                                                                   │  performanceFigures: 1 entries
                                                                                   │    [0]
                                                                                   │      octaneRating: 95
                                                                                   │      acceleration: 2 entries
                                                                                   │        [0]
 per message type ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
message                          count      per s    avg bytes
?                                1          -        4
Car                              3          -        108

Under the tabs, a line says what is tapped, how many messages were read, and what was lost: bytes skipped because the driver had already cleaned them (through the embedded receiver: because its driver never received them), messages dropped because the screen fell behind its reader or they fell off the list (it keeps the newest 5000), and fragmented messages cut by a skip. Each row is one message: its stream position, when the tap read it, its length, match class, message name and the one-line reading. Under the list, the count, rate and average size per message type; ? is anything no schema reads.

The selection follows the newest message until you move it; then it stays on its message while new ones arrive.

Filter, pause and the preview

/ filters the list as on every tab, with a regular expression over the whole row (every column, the decoded line in full, nested messages and the meanings shown included). Lower case ignores case; a capital makes it exact. So 1796343325338615000 keeps only rows where those digits stand together. A pattern that is not a regular expression yet (123.4( while typing) is matched as written, and the filter line says so. The matched text is marked, and the list stays in time order. Space pauses the list (the tap goes on reading; resume shows what arrived).

Enter opens the selected message’s preview beside the list: its position and size, then the message indented, one field per line. While it is open, the movement keys scroll it, and / searches it with a regular expression (lower case ignores case, as the filter does); every match is marked, the current one reversed, and n and N move between them. The search stops at its first 10000 matches, and the title then reads of 10000+. z shows the preview full screen, the list hidden and long lines wrapped, and z again or Esc brings the list back. y copies the preview, as plain text, to the clipboard (Copy and select). Esc while typing the pattern clears it; otherwise Esc closes the preview. No key changes the text.

The list line and the preview are coloured by what each part is: field names cyan, strings and enum names green, what a value means bold, null and absent dim, numbers in the terminal’s own colour. Without colour (NO_COLOR, --color never) only the bold and dim stay. The command line’s output is never coloured this way.

What the values mean

A decoded number says what is on the wire: ts: 1764547200000000000. The terminal UI, and the command line with --interpret, also say what it means: ts: 1764547200000000000 -> 2025-12-01 00:00:00.000000000 UTC (ns, name?). The brackets say how it was worked out: converter (one of yours), schema (what the schema declares), name? (the field’s name) or range? (the value alone). A ? marks a guess.

The rules, and the first that matches wins:

OrderRuleExample
1a converter you registeredevery field of type Price
2a scale the schema declaresa decimal composite; a field whose attribute names its exponent
3the rest of the schemasemanticType="UTCTimestamp", a type named Price, “price in 1e-8”
4the field’s namets, tradePrice, orderQty, spreadBps, fillPct
5the valuea plain integer between 2000-01-01 and 2030-12-31

A count or an id is never read as a date (orderId, timestampCount, size), and a null sentinel (i64::MIN, u64::MAX, the schema’s null value) is never interpreted. Nothing is clamped or rounded to fit: a timestamp past what an i64 of milliseconds holds stays raw, a scaled float keeps all its digits, and a description gives a scale only as 1e-8, 10^-8 or scale 8, within ±18.

Decimals

A composite of exactly two members, a whole number named mantissa and one named exponent (value = mantissa × 10^exponent) or scale (× 10^-scale), is one decimal. The exponent may be on the wire or a constant in the schema. The meaning is shown on the mantissa, so the raw parts stay in sight:

price: { mantissa: 12345 -> 123.45 (1e-2, schema), exponent: -2 }

A field may name the field that holds its exponent instead, with an attribute of a namespace of your own whose local name is exponent or scale (the prefix does not matter):

<messageSchema ... xmlns:q="urn:example:quote">
  ...
  <field name="last" id="4" type="int64" q:exponent="lastExp"/>
  <field name="lastExp" id="5" type="int8"/>

The named field is looked up in the same group entry (or composite) first, then outwards to the message root. The code generator and the XSD check accept such attributes. An exponent that is missing, null or outside ±18 leaves the value raw: it is never guessed.

Messages inside messages

A message read inside another’s var data (the sample’s AppMessage, whose payload holds a Trade or an L2Book) is interpreted too, at any depth. Its paths start with the data field’s and a /: payload/exchangeTimestamp, payload/bids[0].price.mantissa. A framed record inside var data adds its index (payload/0/ts), and a message read after the first adds +/.

Without --interpret, and with no converters file named, the command line’s values are as they are on the wire, byte for byte as before.

In the terminal UI the meanings are shown from the start; i hides them and shows them again. The message’s preview says how each value was worked out:

  ts: 1764547200000000000 -> 2025-12-01 00:00:00.000000000 UTC (ns, name?)

The JSON of a message carries the same, under interpreted: the raw value and what it means, by the field’s path in the message.

{
  "interpreted": {
    "ts": {
      "raw": 1764547200000000000,
      "interpreted": {
        "value": "2025-12-01 00:00:00.000000000 UTC",
        "kind": "timestamp",
        "how": "name",
        "unit": "ns"
      }
    }
  }
}

Your own converters

A program of your own compiles its converters in, with the builder API of ergo_aeron_tools::interpret:

Interpreter::builder()
    .convert_type("Price", scaled(-8))       // every field of type Price
    .convert_field("Trade", "ts", epoch_ns()) // one field of one message
    .convert_name_suffix("_bps", bps())       // every field whose name ends so
    .build()

A converters file says the same, in TOML. --converters FILE (or the environment variable ERGO_AERON_CONVERTERS) reads it, and asks for the interpretation too:

[[rule]]
type = "Price"
converter = "scaled"
exponent = -8

[[rule]]
message = "Trade"
field = "ts"
converter = "epoch"
unit = "ns"

[[rule]]
suffix = "_bps"
converter = "bps"

The built-in converters are epoch (s, ms, us, ns), scaled (an exponent), plain (decimal places), enum, flags, bps, percent, hex, duration and ipv4. A rule that does not make sense is refused with the file, the line and the field, and a file that cannot be read is refused with its path: neither is ignored.

In a pipe

ergo-aeron messages prints the same messages and exits, or follows with --follow (In scripts and pipes):

$ ergo-aeron messages --stream 1001 --schema car.xml --format compact
Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }

In scripts and pipes

Given a subcommand, ergo-aeron prints and exits instead of opening the screen. Each tab has one, from the same table the screen uses, plus health and snapshot:

Read an Aeron media driver's counters, streams, errors and loss without a client, or join a stream through a guarded embedded driver: a front-end-free core, a command line and a terminal UI (ergo-aeron)

Usage: ergo-aeron [OPTIONS] [COMMAND]

Commands:
  counters       Every counter: value, change per second (with --watch) and label (`AeronStat`)
  streams        One row per stream: positions, backlog, slowest subscriber, headroom
  errors         The driver's distinct errors (`ErrorStat`)
  loss           The driver's loss report (`LossStat`)
  driver         Pid, versions, buffer lengths and heartbeat age (`DriverTool`)
  log            A stream's log file as it lies: metadata, term tails and every frame header (`LogInspector`)
  messages       One stream's messages, read from its log file with no subscription (the publisher cannot notice), decoded with --schema. Starts with what the driver still keeps. With --embedded --channel: joined as a guarded receiver through the tool's own driver instead
  recordings     The recordings an archive lists on its control session (needs --control): positions, start and stop, stream, session, channel
  recording      One recording's descriptor and its four positions (needs --control)
  recording-lag  Each active recording's lag behind its stream (C4), from the archive's driver's counters only: no archive session, no client
  replay         One recording's messages, replayed to this tool through the control session (needs --control) and decoded with --schema: what it holds now, or with --follow also what is recorded next. The archive sends it on the control response channel; nothing it holds changes
  archive-dir    An archive directory read as files, never written (needs --archive-dir): `ArchiveTool`'s read commands. With no action, the catalogue header, the mark file and every entry
  history        The directories, streams, channels and schema sources used before, newest first; `history clear` forgets them
  health         One verdict from two reads; exit status 1 when it is ALARM
  snapshot       Everything as one JSON document, for a support bundle
  help           Print this message or the help of the given subcommand(s)

Options:
      --aeron-dir <AERON_DIR>       The driver's aeron directory (default: `AERON_DIR`, else Aeron's default)
      --format <FORMAT>             Output format (default: table on a terminal, json in a pipe) [possible values: table, json, compact, pretty, raw]
      --watch <SECONDS>             Print again every this many seconds, with rates, until interrupted (not `health`)
      --schema <FILE|DIR|URL>       An SBE schema for the Messages tab: a file, a directory of `*.xml`, or an HTTPS URL (with the `http` feature). Repeat for more
      --interpret                   Show what the decoded values mean, beside the raw value: a timestamp as a date, a price as a decimal. A guess is marked with a `?`. The terminal UI shows them without it (`i` hides them)
      --converters <FILE>           A converters file: the rules that say what a value means (TOML). It asks for the interpretation too. The environment variable `ERGO_AERON_CONVERTERS` names one when this is not given
      --interval <MS>               Terminal UI: milliseconds between reads [default: 1000]
      --no-mouse                    Terminal UI: start without capturing the mouse, so the terminal selects text (`M` turns capture on and off while running)
      --stream <STREAM_ID>          Terminal UI: open on this stream's messages
      --session <SESSION_ID>        Terminal UI: with --stream, this session of it
      --channel <URI>               Terminal UI, embedded mode: join --stream on this channel URI
      --embedded                    Start a media driver of the tool's own, in a new directory removed on exit, to join streams named by --channel as a receiver (never started silently). Its stats tabs show that driver unless --aeron-dir names another
      --embedded-dir <DIR>          Embedded mode: the new directory for its driver; must not exist (default: a fresh one beside Aeron's default directory)
      --no-history                  Read and write no history (directories, streams, channels and schema sources used before)
      --color <COLOR>               Colour and icons on tables and `health`, never on json (`auto`: a terminal, off with `NO_COLOR`, on with `CLICOLOR_FORCE`; `never` is plain) [default: auto] [possible values: auto, always, never]
      --icons <ICONS>               Icon set (`auto`: `ERGO_AERON_ICONS`, else the locale, fonts and terminal; a Nerd Font installed is not one in use, so then pick `emoji`) [default: auto] [possible values: auto, nerd, emoji, unicode, ascii]
      --write                       Allow write actions (`driver terminate`); each also needs --confirm (in the terminal UI, the token typed). Without it ergo-aeron only reads
      --action-log <PATH>           Where each write's intent and result are logged (default: `ergo-aeron/actions.log` under `XDG_STATE_HOME`, else `~/.local/state`). A write that cannot be logged is refused
      --archive-dir <DIR>           An Aeron Archive's directory, read as files and never written: the Archive dir tab and `archive-dir` (the archive may be running or stopped)
      --control <URI>               An Aeron Archive's control request channel: the Recordings tab, `recordings` and `recording`, through a client on the tool's own driver with --embedded, else on the attached driver. Read requests only
      --control-stream <STREAM_ID>  The archive's control stream id [default: 10]
      --control-response <URI>      The channel the archive's responses come back on (default: `aeron:ipc` for an IPC control channel, else `aeron:udp?endpoint=localhost:0`)
  -h, --help                        Print help (see more with '--help')
  -V, --version                     Print version

The global flags go before or after the subcommand. ergo-aeron is the installed binary (Install).

Formats

--format table prints aligned columns, numbers right-aligned, as Aeron’s own tools do; it is the default on a terminal. --format json prints one JSON object per row and line; it is the default in a pipe. Labels, channels and error text come from the driver: in a table every control character in them becomes ? (a tab a space), and in JSON they are escaped.

$ ergo-aeron streams --format table
stream  session  pub pos  pub limit  snd pos  snd limit  rcv hwm  rcv pos  subscribers (id@pos)  slowest  behind  headroom %  channel
  1001       77    97920      98304        -          -        -        -  7@65536 9@97920             7   32384         1.2  aeron:ipc?term-length=65536
  2002        5  1048576    1179648  1046528    1179648        -        -  13@1040384                 13    8192        94.1  aeron:udp?endpoint=10.0.0.1:40123
$ ergo-aeron counters --stream 1001 --format table
id  type  value  per s  since mark  label
50     1  98304      -           -  type 1: 5 77 1001 aeron:ipc?term-length=65536
51    12  97920      -           -  type 12: 5 77 1001 aeron:ipc?term-length=65536
52     4  65536      -           -  type 4: 7 77 1001 aeron:ipc
53     4  97920      -           -  type 4: 9 77 1001 aeron:ipc

counters takes --type ID (0: the driver’s system counters), --stream N and --channel TEXT; the last two keep stream position counters only. --explain adds to each counter what it means, what is normal and worrying, what to check next, its ids and its links, as text under the table or as JSON fields (What each counter means).

Colour and icons

The screen and the command line use one palette, from the 16 base ANSI colours (no RGB, no background fills but the selected row), so it reads on a dark or a light background:

StyleMeansWhere
greenhealthy, runningan OK verdict, a healthy stream, a live or valid recording, [READ ONLY]
yellowwarning, lagging, stalea WARN verdict, a lagging stream or recording, a loss row, [PAUSED], [LIVE RECEIVER]
rederror, dead, invalidan ALARM verdict (bold), a dead stream, an error row, an INVALID entry, a watched counter that rose
cyanids and namesstream, session, counter and recording ids, field names
dimsecondary textcounter types, times, channels, sources, the help line
boldheadersevery column header

A row is lagging when its publisher has under half of its window left (or an active recording is over 1 MiB behind its stream), and dead when its publisher is at its limit or an IPC publication has no subscriber. Each tab that shows a status has an icon column before its table: Counters, Streams, Errors, Loss, Driver, Recordings and Archive dir (Messages and Payload have none).

Four icon sets, from the best the terminal can show to plain text:

Meaningnerdemojiunicodeascii
healthyU+F00C✅✓OK
warningU+F071🟡▲WARN
errorU+F057❌✗ERR
laggingU+F017🐌↓LAG
stopped, deadU+F04D⛔■STOP
pausedU+F04C💤‖HOLD
liveU+F111🔴●LIVE
connectedU+F1E6🟢◆CONN
streamU+F0EC🌊≈STRM
publicationU+F093📤▸PUB
subscriptionU+F019📥◂SUB
recordingU+F130📼◉REC
archiveU+F187📦▤ARCH
driverU+F013🔧⌂DRV
counterU+F292🔢#CTR

Each set has one fixed width (1 cell, 2 for emoji, 4 for the ASCII tags), and the icon sits in a column of its own, never inside an aligned number.

--icons nerd|emoji|unicode|ascii|auto chooses the set; so does the environment variable ERGO_AERON_ICONS, and the flag wins over it. With auto, which a program cannot do perfectly, it goes by:

  1. no UTF-8 locale (LC_ALL, LC_CTYPE, then LANG), or TERM=dumb: ascii;
  2. nerd when a Nerd Font is installed (on macOS a Nerd Font file name in ~/Library/Fonts, /Library/Fonts or /System/Library/Fonts, one folder level deep; elsewhere fc-list naming Nerd Font, NFM or NFP, given half a second), or NERD_FONT=1. The answer is kept 24 hours in icons-probe beside the history file (--no-history keeps none);
  3. emoji on a terminal known to draw it (TERM_PROGRAM of iTerm.app, Apple_Terminal, WezTerm, vscode or ghostty; kitty);
  4. otherwise unicode.

Installed is not selected: a program cannot read which font the terminal uses. If the terminal is set to another font, the Nerd icons draw as empty boxes: give --icons emoji (or set ERGO_AERON_ICONS) and it stays that way.

Colour on the command line follows --color auto|always|never:

  • auto colours when standard output is a terminal, unless NO_COLOR is set to anything non-empty. CLICOLOR_FORCE (set, not 0) colours a pipe too; NO_COLOR wins over it, CLICOLOR=0 and TERM=dumb turn it off.
  • always colours whatever the environment says; never prints plain text with no icons.

Colour and the icon column go on tables, health, history and the archive commands, only on a terminal or when forced; the icons come from --icons or the detection above. --format json, a pipe, and --color never print the plain text the book shows, byte for byte. In the terminal UI NO_COLOR keeps bold, dim and reversed text and drops every colour. Secondary text is dimmed (SGR 2) in the terminal’s own foreground colour, so it reads on any theme. The messages and log output print plain; the archive-dir segment, frame and disk tables and recording-lag only get a bold header.

--watch SECONDS prints again every so many seconds until interrupted; from the second read on, per s is the change per second (a single run, as above, has no earlier read and prints -). health reads twice by itself and has no --watch: giving it one is an error. A reader that stops reading ends the run quietly with status 0:

ergo-aeron counters --watch 1 | head -1
ergo-aeron streams | jq 'select(.headroom_pct != null and .headroom_pct < 10)'

Copy and select

The terminal UI captures the mouse (clicks pick tabs, rows and columns), so the terminal cannot select text while it does. M turns capture off, and the top line says [MOUSE OFF ...]; select and copy with the terminal as usual, then M turns it on again. --no-mouse starts with it off. The terminal is given its mouse back when the tool exits.

y copies the open message preview, as plain text with no colour, to the clipboard. It sends the terminal the OSC 52 sequence, which the terminal decodes itself, so it also works over ssh and kubectl exec. The terminal has to accept OSC 52 (some ask for it to be allowed in their settings). Inside tmux it needs set -g set-clipboard on: tmux’s manual says its default, external, ignores the sequence from applications.

One copy holds at most 55,000 bytes, which stays within what terminals accept: a longer preview is cut after a whole line, and the status line says how many lines were copied. For the whole of a large message, use ergo-aeron messages.

health and snapshot

health reads twice, --between MS apart (default 1000), and prints one verdict with its reasons (what it watches):

$ ergo-aeron health --format table
ALARM
  Sender flow control limits, i.e. back-pressure events: rose by 3 to 3

snapshot prints everything as one JSON document (driver, health, streams, counters, errors, losses and any part of the read that failed), for a support bundle.

messages

messages --stream N prints a stream’s messages, read from its log file with no subscription (why), decoded with --schema (files, directories, or with feature http HTTPS URLs; repeatable). Without --stream it takes the driver’s only stream, or names them all and exits 2. It prints what the driver still keeps of the stream and exits; --follow then keeps printing new messages until interrupted. --session S picks one session of a stream with several. With --embedded, --channel URI --stream N --follow joins the stream through the tool’s own driver as a guarded receiver instead (Attached or embedded); a receiver has nothing retained, so --follow is needed and --counts is not offered. Without --schema, a stream or channel read before has its schemas offered on standard error: schemas used with stream N last time: ....

$ ergo-aeron messages --stream 1001 --schema car.xml --format compact
Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
Exact Car { serialNumber: 1234, modelYear: 2013, available: T, code: A, someNumbers: [10, 20, 30, 40, 50], vehicleCode: "ABCDEF", extras: sportsPack|cruiseControl, engine: { capacity: 2000, numCylinders: 4, maxRpm: 9000, manufacturerCode: "123", fuel: "Petrol" }, fuelFigures: [{ speed: 30, mpg: 35.9 }, { speed: 60, mpg: 25.0 }], performanceFigures: [{ octaneRating: 95, acceleration: [{ mph: 30, seconds: 4.0 }, { mph: 60, seconds: 7.5 }] }], manufacturer: "Honda", model: "Civic VTi" }
--formatPrints
table (terminal default)position, time read, length, match class, message and the one-line reading
json (pipe default)one object per message: position, seen_ms, session, stream, length, class, message, the one-line reading and the inspector’s own JSON reading
compactthe one-line reading
prettywhere the message sits, then one field per line
raweach message as a 4-byte little-endian length and its bytes; refused on a terminal

raw is a framing sbe-inspect detects, so a capture can be decoded later or elsewhere:

ergo-aeron messages --stream 1001 --follow --format raw > capture.bin
sbe-inspect schemas/ < capture.bin

--counts prints the count, rate and average size per message type instead of the messages (not with --follow). A reader that falls behind the stream (a slow pipe) skips forward to data the driver still has and says so on standard error, fell behind: skipped N bytes ..., at most once a second; a stalled pipe never holds the publisher. Bytes the embedded receiver never got are said the same way, lost: skipped N bytes .... What was not yet said when the run ends is said then, also when Ctrl-C, SIGTERM or SIGHUP ends it. The run has 5 seconds from such a signal to end: one still running then, whether stuck (writing to a pipe or terminal nobody reads) or still writing to a slow reader, is ended with status 130 and says nothing more. compact, pretty and raw are for messages only.

--interpret shows what each value means beside its raw value, and --converters FILE (or the environment variable ERGO_AERON_CONVERTERS) gives the rules that say so in a TOML file (what the values mean), messages nested in var data included. Without --interpret, and with no converters file named, the output is what it was. The terminal UI shows the meanings without the flag; i hides them.

log

log --stream N prints a stream’s log file as it lies, --file PATH a log file with no driver (what it shows). Without either it takes the driver’s only stream, or exits 2 naming them. --format table prints the metadata, then one frames table; --format json prints {"metadata": {...}} on the first line, then one {"frame": {...}} per frame header, each with its index (term partition), offset, the header fields, payload and note (why the term’s walk stopped there, else null). Each frame prints as it is read, so memory stays flat on a log of any size. --dump BYTES (default 65536), --ascii and --scan-over-zeroes are LogInspector’s options; --dump-all shows every payload in full. --file refuses anything but a regular file.

ergo-aeron log --stream 1001 --scan-over-zeroes | jq -c 'select(.frame.type == 1) | .frame.offset'

driver terminate

The one write action: refused unless given --write and --confirm PID@START_MS with the driver’s pid and start time (how it works).

ergo-aeron driver terminate --dry-run   # the preview and the token; sends nothing
token=$(ergo-aeron driver --format json | jq -r '"\(.driver.pid)@\(.driver.start_ms)"')
ergo-aeron driver terminate --write --confirm "$token" --wait 5000

It prints termination requested ... on standard output, then ... has stopped once the driver is gone; what it prints never changes the exit status, so a reader that closes the pipe early cannot make it exit 0. The path of the action log is named on standard error. In the terminal UI the same action is behind --write and the typed token (In the terminal UI).

The archive commands

recordings and recording ID read an Aeron Archive over its control session (--control URI), recording-lag the archive’s driver’s counters, and archive-dir ... an archive directory’s files (--archive-dir DIR), ArchiveTool’s read commands among them (Archive tabs). Each prints --format table or json once (no --watch). replay ID (also --control) prints a recording’s messages in the formats of messages, and with --follow goes on while it records (payload).

ergo-aeron --archive-dir /data/archive archive-dir describe --format json | jq -r 'select(.stream_id == 1001) | .recording_id'
ergo-aeron --archive-dir /data/archive archive-dir verify || echo "Java's verify would mark an entry INVALID"

history

history lists the aeron directories, streams, channels, schema sources, archive directories and archive control channels used before, newest first, as a table or JSON lines; history clear forgets them; --no-history (any command) reads and writes none (history).

Exit status

StatusWhen
0printed; or the reader closed the pipe (not for driver terminate); or a followed stream closed; for driver terminate, only that the driver stopped: its cnc.dat gone, its heartbeat cleared or another driver started there; or its --dry-run printed
1health judged ALARM; or driver terminate was sent and, after --wait, the driver still runs, does not answer (heartbeat stale, files still there: it may be paused) or cannot be read; or an interrupt (--embedded only) ended the --wait: it prints that the termination was requested and is not confirmed; or archive-dir verify found an entry Java’s verify would mark INVALID
2for archive-dir, no --archive-dir, or a catalogue, mark file or segment that cannot be read or holds a length Aeron never writes (what was printed before it stands); for recordings, recording and replay, no --control, a control channel that is not an aeron: URI, no archive answering in 10 s, no such recording, an aeron:ipc control channel with --embedded, or a build without the archive control reader; for replay, also a position outside the recording or inside a frame, --format raw to a terminal, a schema that does not load, or a replay that the archive fails, never connects or ends short of what was asked (what was printed before it stands)
2in embedded mode, the driver did not start, its directory exists, or the channel is refused (fc=min, IPC, a spy, a parameter given twice), or AERON_CONGESTIONCONTROL_SUPPLIER names a supplier other than default or static; a --channel without --embedded; history with history off; an interrupt (--embedded only) between the two reads of health --between, which prints no verdict; no driver could be read at the directory (health then prints no verdict, only the reason), or bad arguments (including health --watch), or no subcommand with stdout not a terminal (the screen is never written into a pipe); for messages and log, also a stream that is not there or cannot be chosen; for messages, a schema that does not load, or --format raw to a terminal; for log, a log file that is not a regular file, cannot be read or fails its checks; for driver terminate, a refusal (no --write, no --confirm, a token that does not match, a driver that is no longer the one read or whose heartbeat is already stale, or an action log that cannot be written, or an interrupt before the request was sent, or --embedded with no other driver’s directory in --aeron-dir: nothing was sent) or a request that could not be written
130with --embedded, messages --follow or replay --follow, the run was still going 5 seconds after SIGINT, SIGTERM or SIGHUP and was ended; an embedded driver’s directory may be left behind

Diagnostics go to standard error, one line each, starting ergo-aeron:; a control character in them (a directory name, Aeron’s text) shows as ?. health --format json spells the verdict as the table does (OK, WARN, ALARM).

Driver tabs and Aeron’s own tools

Each driver tab stands in for one of the tools that ship with Aeron 1.54.3, reading the same files, so it works wherever those tools do; Messages has no Aeron counterpart (Live messages):

TabSubcommandAeron 1.54.3 toolShows
CounterscountersAeronStatevery counter: value, change per second, change since the mark
StreamsstreamsStreamStat, BacklogStatone row per stream: every position, backlog, the slowest subscriber and the publisher’s headroom
ErrorserrorsErrorStatdistinct errors with their count, first and last time
LosslossLossStatper stream: gaps and bytes lost
DriverdriverDriverTool (pid, CnC metadata)pid, versions, buffer lengths, heartbeat age
Messagesmessagesnone (LogInspector reads the same log file, offline)one stream’s messages, read from its log file with no subscription, decoded with the schemas given; counts per message type
Recordingsrecordingsnone (the archive client’s listRecordings and position queries)an archive’s recordings from its control session, read requests only: positions, start and stop, stream, channel, session; each active recording’s lag
Payloadreplaynone (the archive client’s startReplay)one recording’s messages, replayed through the control session and decoded with the schemas given; live while it records
Archive dirarchive-dirArchiveTool (describe, describe-all, count-entries, capacity, pid, errors, dump, verify without marking)an archive directory read as files, never written: catalogue, mark file, segment files, disk use and time until full

Two commands are not tabs: the log inspector, and the one action that writes, both from tables in the code:

CommandAeron 1.54.3 toolAccessNeeds --confirmWhat it does
logLogInspectorReadnoone stream’s log file as it lies (metadata, term tails, every frame header and its payload), read with no client; also a log file given by path
driver terminateDriverTool terminateWritethe driver PID@START_MSasks the driver to stop, through its CnC file; the driver’s termination validator decides, and Aeron’s default denies

All of them read cnc.dat in the driver’s directory (and loss-report.dat for Loss), mapped read-only; Messages and log also read the stream’s log file. No client is started (in embedded mode only the tool’s own driver gets one, Attached or embedded), and nothing is written to a driver unless the tool is given --write and driver terminate is confirmed (below).

Aeron’s C reader trusts the lengths a file carries, and a wrong one crashes it, so ergo-aeron checks them first. A counter label that does not fit its record, a counter value that does not fit the values buffer, or a to-driver buffer Aeron cannot read a heartbeat from, refuses the read (exit status 2, cannot read the Aeron driver at ...: ...); that is not “driver gone”. A driver that closed cleanly leaves its directory with the heartbeat cleared, which is ALARM (driver gone). A damaged error log or loss report is left out and named in the read’s notes, which turn the health line to WARN. A label that is not UTF-8 is shown with the bad bytes replaced by U+FFFD, and warns the same way.

Counters

One row per allocated counter: id, type id, value, change per second since the previous read, change since the mark, and label. Counters are running totals, so the rate and the mark are what show a test’s effect. Enter on a row explains the counter and links it to its owner, stream, recording and siblings (What each counter means).

Streams

One row per stream, keyed as BacklogStat keys it: session and stream id, on IPC or on the network. The publisher’s channel is shown; subscribers may have written the same channel differently (aeron:ipc against aeron:ipc?term-length=65536) and still count on the same row.

ColumnFrom
pub pos, pub limitthe publisher’s position and limit: it cannot publish past the limit
snd pos, snd limita network publication’s sender position and flow-control limit
rcv hwm, rcv posa network image’s receiver high-water mark and position
subscribers (id@pos)every subscriber on this driver: registration id and position
slowest, behindthe subscriber furthest behind what it follows (the publisher for IPC and spies, the receiver’s high-water mark for an image), and by how many bytes
headroom %how far the publisher is from back pressure, as a share of its window: (limit - position) / (limit - base); 0 once it has reached the limit

The base is what moves the limit on. On IPC it is the lowest subscriber; on a network publication it is the lowest of the sender and any spy on this driver. So an IPC row with headroom near 0 and one subscriber far behind names the subscriber holding the publisher back.

slowest is the subscriber with the most bytes behind (never below 0: a subscriber read ahead of its head is 0 behind). When several tie, as when all have caught up, it is the one at the lowest position, then the lowest registration id, so the same read always names the same subscriber.

Errors and Loss

Errors lists each distinct error the driver logged, with its count and its first and last time (UTC); a multi-line error is joined with |. Loss lists, per stream and source, the gaps a receiver filled and the bytes lost.

Driver

The pid, the Aeron version the driver reports, the CnC layout version, the start time, the age of the driver’s heartbeat, the client liveness timeout, and the buffer lengths. The driver stamps its heartbeat about once a second.

Log inspector

ergo-aeron log --stream N reads the stream’s log file (a publication’s, else an image’s) as Aeron’s LogInspector does, and --file PATH reads a log file with no driver, such as a copy. It prints the log’s metadata, each term partition’s tail counter, then every frame header from the start of each term with its payload:

$ ergo-aeron log --file stream-1001.logbuffer --dump 16 --format table
field              value
log                stream-1001.logbuffer
correlation id     3
is connected       1
active transports  0
initial term id    0
term count         0
active index       0
term length        65536
MTU                1408
page size          4096
EOS position       9223372036854775807
default header     frame-length=0 version=0 flags=11000000 type=1 term-offset=0 session-id=77 stream-id=1001 term-id=0 reserved-value=0
tail 0             term id 0 term offset 320 raw tail 320 position 320
tail 1             term id -2 term offset 0 raw tail -8589934592 position -131072
tail 2             term id -1 term offset 0 raw tail -4294967296 position -65536

index      offset  frame length  version  flags      type  term offset      session       stream      term id              reserved  payload
    0           0           140        0  11000000      1            0           77         1001            0                     0  2900010001000100D2040000DD070141
    0         160           140        0  11000000      1          160           77         1001            0                     0  2900010001000100D2040000DD070141
    0         320             0        0  00000000      0            0            0            0            0                     0  end: frame length 0 (not written yet, or cleaned by the driver; --scan-over-zeroes looks past it)
    1           0             0        0  00000000      0            0            0            0            0                     0  end: frame length 0 (not written yet, or cleaned by the driver; --scan-over-zeroes looks past it)
    2           0             0        0  00000000      0            0            0            0            0                     0  end: frame length 0 (not written yet, or cleaned by the driver; --scan-over-zeroes looks past it)

The two unused partitions hold the term ids the driver starts them with, so their positions are negative, as LogInspector shows them. Each term’s walk stops at the first frame that is not whole, with a note: a zero length, a frame still being written (negative length), a length below the 32-byte header, or one that runs past the term. A zero length is either not written yet or already cleaned. An IPC publication’s driver zeroes the term right behind its slowest subscriber, so on a stream whose subscribers keep up the start of the active term is zeros and the frames lie further on. A network publication’s driver cleans only up to one term length behind the sender’s position (or its slowest receiver’s), so the active term’s frames stay readable. --scan-over-zeroes skips empty slots and finds them, and does not print the slots (LogInspector prints each). --dump BYTES caps the payload per frame (default: 65536, an MTU; --dump-all shows every byte, however long a frame a damaged or hostile file claims) and --ascii prints it as text, every control character as ?. Frames print one at a time, the table with fixed column widths, so memory stays flat however large the log. A file that is not a regular file (a FIFO, a device) is refused. The metadata is checked before use (term length and page size powers of two in range, the file length they make, MTU and window in range), and a log that fails is refused with the reason. On the Streams tab, Enter shows the log’s main fields (path, term length, MTU, initial term id, active index, end-of-stream position and each tail) above the row’s own columns.

Terminate

What each write action changes, from the code’s action table:

ActionReversibleCreatesDeletesFreesGrows
driver terminatenononothing on disk; in-flight data of the driver’s clients is lostnothingnothing

ergo-aeron driver terminate asks the driver to stop, as DriverTool terminate does: it writes a terminate command into the driver’s to-driver buffer, so it needs cnc.dat writable. It is refused, with exit status 2 and nothing sent, unless it is given both --write and --confirm PID@START_MS, the driver’s pid and its start time in milliseconds from the CnC file, both as ergo-aeron driver --format json shows them (or --dry-run, below). The start time is there because the pid alone names nothing in a container, where a driver started as the entry point is pid 1 in every pod. A bare pid, or 1, is refused with a message that prints the exact token to use. Without --write it is refused before the driver’s files are read; a wrong token (from a wrong --aeron-dir, say) is refused after a read-only read. The pid and start time are read again just before the request is written, and a driver that restarted in between is not asked. A driver whose heartbeat is already older than its liveness timeout is not running: that is refused too, with nothing sent.

--dry-run prints what would be done, the token that confirms it and the command line that does it, then exits 0. It needs no --write, and with it nothing is ever sent or logged, whatever else is on the command line. --write without --confirm prints the same on standard error and exits 2. It is the tool’s own prediction from its read: the driver decides.

With --embedded, nothing is written to the tool’s own driver: driver terminate is refused, and the terminal UI offers no action, unless --aeron-dir names another driver’s directory.

The action log

Every write that passes the gate is logged: an intent line before anything is sent, a result line after (done, unconfirmed or refused), one JSON object per line with the time, the action, its target token and the directory. The file is ergo-aeron/actions.log under XDG_STATE_HOME, else ~/.local/state/, readable by its owner only; --action-log PATH moves it, and --no-history does not turn it off. If the intent line cannot be written and synced, the action is refused and nothing is sent. So is a path that is not a regular file, is a symbolic link, belongs to another user, gives its group or others any access, or already holds something that is not an action log: the tool never appends to other data. A new log’s directory is synced too. A refusal at the gate (no --write, no or wrong token) is not logged, nor is a dry run. An intent line with no result line means the tool was stopped in between: check the driver. In a container with a read-only home, point --action-log at a writable volume.

In the terminal UI

Start it with --write (the top line says [WRITE]), open the Driver tab and press a (or F2): the menu lists the tab’s write actions. Enter shows the preview and a box; type the whole token and press Enter. Any other text keeps the box open and sends nothing; Esc cancels. The request runs off the screen’s thread, and a line at the foot says waiting, then done, unknown or refused with the log’s path (Esc clears it). The write is the command line’s own: the same gate, checks and log. One confirmation sends at most once, and one write runs at a time. While it waits, Esc and q do not quit; Ctrl-C does. Quitting (or, with --embedded, a signal) before the request is sent sends nothing and logs cancelled before sending; nothing was sent; after it, it stops the wait, logs it as unconfirmed and prints the line. Without --embedded a signal ends the process at once, so a log can be left with an intent line and no result line.

One narrow race stays. After that last check, Aeron’s own request_driver_termination opens cnc.dat again by path to write the command, and the tool cannot hand it the file it already checked (comparing the file’s device and inode before the write would not help: the swap can come after the last look). If the driver exits and another starts in the same directory in those microseconds, the new one receives the request. It still needs an allowing termination validator to act on it. In a script: use the --confirm token of this run (never a fixed one), keep the directory dedicated to one driver (no supervisor restarting a driver there while the request is in flight), and check afterwards, with ergo-aeron driver, that it is the driver you meant that stopped and no other runs.

The driver decides. Aeron’s default termination validator denies every request. The C driver aeronmd started with AERON_DRIVER_TERMINATION_VALIDATOR=allow runs its termination hook, which stops it; a driver embedded in an application stops only if that application’s hook does. ergo-aeron waits up to --wait MS (default 5000) and says which happened: exit 0 only once the driver has stopped (its cnc.dat gone, its heartbeat cleared by a clean close, or another driver started there); exit 1 when it still runs, when it does not answer (its heartbeat is older than its liveness timeout but its files are still there: it may be paused, so do not start another driver in the same directory), or when its CnC file is there but unreadable.

Health

The line under the status, and the health subcommand, give one verdict:

VerdictWhen
ALARMthe heartbeat is older than the client liveness timeout (driver gone); the last read failed (on the screen: the health subcommand exits 2 with the reason and prints no verdict); or a watched counter rose between the last two reads
WARNa watched counter is non-zero since the driver started or since the mark; the driver’s CnC version, Aeron version or number of system counters differs from the Aeron this tool was built with, so labels may not match; or part of a read failed
OKnone of these

Watched counters, which stay at zero on a healthy driver: sender flow-control limits (back-pressure events), unblocked publications and control commands, client liveness timeouts, invalid packets, short sends, retransmit pool overflow, images rejected, error frames received, the three proxy fail counts, the conductor, sender and receiver cycle-time threshold counts, and an archive’s error count and cycle-time threshold count. When one is flagged, the reasons also list the non-zero maximum cycle times (conductor, sender, receiver, archive) and the archive recorder’s maximum write time.

What each counter means

The Counters tab lists every counter in the driver’s cnc.dat. A counter’s number alone says little, so ergo-aeron explains the one you select: what it counts, what its value means, which values are normal and which are worrying, what to check next, the ids it carries, and what it links to.

In the terminal

Select a counter and press Enter. Below the row’s own columns the detail shows:

LineWhat it says
counterThe counter’s short name, and how far Aeron’s source backs the text (below)
whatWhat it counts or tracks, in Aeron’s words where it has them
meaningWhat the value stands for
value isThe current value decoded, for a state, a channel status or the driver’s version
normal, worryingWhat a healthy and a worrying value look like
supportWhat a person debugging the node should read or check next
idsOwner id (the client), registration id, stream, session, channel, recording, archive, cluster, service, cluster session and snapshot recording ids, when the counter carries them
linksThe entities the counter leads to, one line each (below)
key holdsWhat the counter’s key contains
sourceThe Aeron constant the entry comes from

The detail is long, so ] scrolls it down and [ up (F10, F11). r marks the next link and f jumps to it: to a counter on the Counters tab, a stream on the Streams tab, or a recording on the Recordings or Archive dir tab. A recording link with no archive tab open says so in the status line and stays where it is. A filter that hides the target is cleared for the jump.

On the command line

ergo-aeron counters --explain prints the table, then one block per counter with the same lines. The filters (--type, --stream, --channel) cut the list, not the links: an owner or a sibling counter is found in the whole read. With --format json each counter’s object keeps its fields and gains:

FieldHolds
description, meaning, normal, worrying, supportThe same text
classDocumented, Listed or Unknown
explained_as, value_text, source, keyThe short name, the decoded value, the Aeron constant and what the key holds
idsThe ids the counter carries
relatedThe links: label, text and target (null for a fact, or an entity that is gone)

Output without --explain is unchanged.

How far to trust the text

Each entry says how far Aeron’s own source backs it, so a guess is never passed off as documentation:

  • Documented. The constant has a description in AeronCounters.java and code in the Aeron tree allocates the counter. The key layout and the states are read from that code. The advice (normal and worrying values, what to check) restates what the documented behaviour implies.
  • Listed only. The constant is in AeronCounters.java and nothing else in the Java or C sources uses it (kernel-bypass and encryption transports, the cluster standby and transition module, selector and sequencer counters). The entry gives the constant’s own line and says nothing about its values.
  • Unknown. An id this Aeron does not define, from a newer driver or from an application (type ids from 1000 are free for applications): shown as not documented for this Aeron version: type id N, label ....

The catalogue was read from Aeron 1.54.3. A tool built against another Aeron fails its tests until the catalogue is read again. System counters are found by their id, because that is how the driver numbers them; every other counter by its type id.

LinkWhenLeads to
ownerThe counter has an owner idThe owner’s client-heartbeat counter, with its age; or a line saying the client no longer exists
ownsA client-heartbeat counterThe first eight counters that client owns, and how many more
streamA stream position counterThe Streams row for its stream and session
siblingA stream position counterThe stream’s other counters, with their owners
lagA stream position counterThe gaps between the stream’s positions (below)
channel statusA stream position counter, or a local socket addressThe snd-channel or rcv-channel counter with the same registration id, and its status
stream, local addressA channel status counterThe streams registered under it, and its bound socket address
recording, recorded streamA rec-pos counterThe recording, and the stream being recorded with its lag
recorded byA stream position counterThe rec-pos counters that record the stream, with the lag
archiveAn archive counterThe other counters of the same archive id
cluster, cluster counterA cluster counterA summary of the cluster’s role, election state, module state, commit position and leadership term, and its other counters
snapshot recordingA cluster recovery stateThe recording each service loads on start

The gaps in lag are computed only when both positions exist: publisher limit minus publisher position (headroom before back pressure), publisher position minus sender position (what the sender still has to send), sender limit minus sender position, receiver high-water mark minus receiver position (loss not yet repaired), and for each subscriber the stream’s head minus its position. The head is the publisher for IPC and for a spy, the receiver’s high-water mark for a network image.

The reference

These entries are Aeron 1.54.3’s counters, each tied to the constant in AeronCounters.java it comes from. documented means the constant has a description there and code in the Aeron tree allocates the counter; listed only means the constant is there and nothing else in the tree uses it.

System counters (type id 0)

Found by their counter id, which is their system counter id: the driver allocates them first, in this order.

CounterWhat it counts, and what the value meansNormalWorryingCheck next
bytes sent id 0Bytes sent over the network. Total bytes this driver has sent on the wire since it started.Rises with outbound traffic; the per-second change is the send rate.Flat while publications are active, so the sender is stalled; or a rate far above the expected load.Compare the per-second change with the peer’s ‘Bytes received’; if sent rises and the peer’s does not, look at the network between them.
bytes received id 1Bytes sent over the network (the constant’s description repeats the one for bytes sent; the counter counts bytes received). Total bytes this driver has received from the wire since it started.Rises with inbound traffic; the per-second change is the receive rate.Flat while the peers say they are sending.Compare the per-second change with the sender’s ‘Bytes sent’; a gap is loss or a blocked path (see ‘NAKs sent’ and the Loss tab).
receiver proxy fails id 2Failed offers to the receiver proxy. Times the driver could not hand a command to the receiver agent because its command queue was full.0.Any rise: the receiver agent is not draining its queue.Check the receiver’s max cycle time and its ‘exceeded’ counter; see whether the receiver thread is starved of CPU.
sender proxy fails id 3Failed offers to the sender proxy. Times the driver could not hand a command to the sender agent because its command queue was full.0.Any rise: the sender agent is not draining its queue.Check the sender’s max cycle time and its ‘exceeded’ counter; see whether the sender thread is starved of CPU.
conductor proxy fails id 4Failed offers to the conductor proxy. Times the driver could not hand a command to the conductor agent because its command queue was full.0.Any rise: the conductor agent is not draining its queue.Check the conductor’s max cycle time and its ‘exceeded’ counter; see whether the conductor thread is starved of CPU.
NAKs sent id 5NAKs sent back to senders requesting re-transmits. Negative acknowledgements this driver’s receiver sent because it saw a gap in a stream.0 or very low on a clean network.A steady rise: packets are being lost or reordered on the way in.Open the Loss tab for the streams and sources; check the network path, NIC drops and socket buffer sizes on this host, and the sender’s ‘Retransmits sent’.
NAKs received id 6NAKs received from receivers requesting re-transmits. Negative acknowledgements this driver’s sender received from receivers that saw gaps.0 or very low on a clean network.A steady rise: receivers are missing data this host sent.Check ‘Retransmits sent’ follows it, then the receivers’ ‘NAKs sent’ and the network path to them.
status messages sent id 7Status messages sent back to senders for flow control. Flow-control status messages this driver’s receiver sent to senders.Rises while subscribers consume data.Flat while an image is active: the sender will stop at its flow-control limit.Check the subscribers’ positions on the Streams tab and whether the receiver agent is stalled.
status messages received id 8Status messages received from receivers for flow control. Flow-control status messages this driver’s sender received from receivers.Rises while receivers consume data.Flat while publications are active: the sender’s limit is not advancing and publishers see back pressure.Check the receivers’ ‘status messages sent’ and the network path back from them; compare ‘Sender flow control limits’.
heartbeats sent id 9Heartbeat data frames sent to indicate liveness in the absence of data to send. Data-less frames the sender sent to show a publication is alive when it has nothing to send.Rises slowly on an idle publication.Flat on a publication that should be alive, or a rate far above the idle one.Compare with the peer’s ‘Heartbeats received’; a mismatch is loss on the path.
heartbeats received id 10Heartbeat data frames received to indicate liveness in the absence of data to send. Data-less frames the receiver got from senders to show their publications are alive.Rises slowly on an idle stream.Flat on an idle stream that should be alive: its image may time out.Compare with the sender’s ‘Heartbeats sent’; see the image liveness timeout (aeron.image.liveness.timeout).
retransmits sent id 11Data packets re-transmitted as a result of NAKs. Packets the sender sent again because a receiver NAKed them.0 or very low.A steady rise: the path to a receiver loses data.Read it with ‘NAKs received’ and ‘Retransmitted bytes’; check ‘Retransmit Pool Overflow count’ for retransmits that were refused.
flow control under runs id 12Packets received which under-run the current flow control window for images. Packets that arrived behind the receiver’s current window (data it had already moved past).0 or very low.A rise: stale or duplicated packets are arriving, for instance after retransmits or a slow receiver.Read it with the Loss tab and ‘Retransmits sent’; check the subscribers’ lag on the Streams tab.
flow control over runs id 13Packets received which over-run the current flow control window for images. Packets that arrived beyond the receiver’s current window (data further ahead than it will accept).0 or very low.A rise: a sender is sending past the window the receiver advertised.Check the receiver window and the sender’s flow-control settings, and the subscribers’ lag on the Streams tab.
invalid packets id 14Invalid packets received. Packets the driver discarded because they did not parse as Aeron frames.0.Any rise: something is sending non-Aeron or corrupted traffic to a port the driver listens on.Find the sender with a packet capture on the endpoint port, and check the Errors tab at the same time.
errors id 15Errors observed by the driver and an indication to read the distinct error log. Number of errors the driver logged; each distinct error is in the driver’s error log.0.Any rise since the last look.Open the Errors tab: it lists each distinct error with its count and first and last time. Read the newest first.
short sends id 16Socket send operations which resulted in less than the packet length being sent. Times the operating system sent fewer bytes than the packet’s length.0.Any rise: the socket send path is under pressure.Check the socket send buffer size and NIC or kernel send errors on this host.
free fails id 17Attempts to free log buffers no longer required by the driver which are still held by clients. Times the driver tried to free a log buffer a client still had mapped.0 or very low.A rise that does not stop: clients keep resources the driver wants back.Find clients that hold on to closed publications or images (see the client heartbeats on the Counters tab).
sender flow control limits id 18The times a sender has entered the state of being back-pressured when it could have sent faster. Back-pressure events: times the sender reached the limit flow control gave it while it could have sent more.0, or flat on a stream whose receivers keep up.A rise: receivers are not consuming or acknowledging fast enough for the sender.Open the Streams tab and look at the slowest subscriber and the publisher’s headroom; see the per-stream ‘snd-bpe’ counter for which stream.
unblocked publications id 19The times a publication has been unblocked after a client failed to complete an offer within a timeout. Times the driver forced a publication forward because a client started an offer and did not finish it in time.0.Any rise: a publishing client stalled or died in the middle of an offer.Find the publishing client that stalled around the time of the rise; the timeout is aeron.publication.unblock.timeout.
unblocked commands id 20The times a command has been unblocked after a client failed to complete an offer within a timeout. Times the driver skipped a client command whose write to the command buffer was never completed.0.Any rise: a client stalled or died while sending a command to the driver.Find the client that stalled around the time of the rise; check the Errors tab.
possible TTL asymmetry id 21The times the channel endpoint detected a possible TTL asymmetry between its config and new connection. Times a new connection’s TTL looked different from this endpoint’s configured TTL.0.Any rise: peers on a multicast channel are configured with different TTLs.Compare the ttl in the channel URIs on both ends.
controllable idle strategy id 22The status of the ControllableIdleStrategy if configured. The status of the driver’s controllable idle strategy, if one is configured; it is a code Aeron’s source does not decode here.Whatever you set it to; 0 when no controllable idle strategy is configured.A value you did not set.Check which idle strategy the driver was started with (aeron.threading.mode and the idle strategy properties).
loss gap fills id 23The times a loss gap has been filled when NAKs have been disabled. Times a receiver filled a gap with padding instead of asking for a retransmit, because NAKs are disabled for the channel.0 unless NAKs are disabled on purpose.Any rise: data in those gaps was dropped on purpose and never delivered.Check the channel’s loss handling (unicast NAK disabled, or a multicast loss generator) and the Loss tab.
client timeouts id 24The Aeron clients that have timed out without a graceful close. Clients the driver dropped because their heartbeat stopped for longer than the client liveness timeout.0.Any rise: a client process died, hung or was starved of CPU long enough to miss its heartbeats.Find the client by its owner id on the Counters tab (its ‘client-heartbeat’ counter is gone once it times out); the timeout is aeron.client.liveness.timeout (see the Driver tab).
resolution changes id 25The times a connection endpoint has been re-resolved resulting in a change. Times a hostname in a channel resolved to a different address than before.0, or rare when addresses move on purpose.A rise that was not planned: DNS answers are changing under the driver.Check the name service for the endpoints involved.
conductor max cycle time id 26The maximum time spent by the conductor between work cycles. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Far below the threshold, whose property is aeron.driver.<agent>.cycle.threshold (conductor, sender or receiver).At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
conductor cycle threshold exceeded id 27The number of times the cycle time threshold has been exceeded by the conductor in its work cycle. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
sender max cycle time id 28The maximum time spent by the sender between work cycles. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Far below the threshold, whose property is aeron.driver.<agent>.cycle.threshold (conductor, sender or receiver).At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
sender cycle threshold exceeded id 29The number of times the cycle time threshold has been exceeded by the sender in its work cycle. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
receiver max cycle time id 30The maximum time spent by the receiver between work cycles. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Far below the threshold, whose property is aeron.driver.<agent>.cycle.threshold (conductor, sender or receiver).At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
receiver cycle threshold exceeded id 31The number of times the cycle time threshold has been exceeded by the receiver in its work cycle. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
name resolver max time id 32The maximum time spent by the NameResolver in one of its operations. The longest a single name resolution took, in nanoseconds.Small: resolution is normally quick.Large: a lookup blocked the thread that asked for it.Check the DNS or name service the driver uses, and the ‘exceeded’ counter beside it.
name resolver threshold exceeded id 33The number of times the time threshold has been exceeded by the NameResolver. How many name resolutions took longer than the configured threshold.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with a slow DNS or name service; see ‘name resolver max time’.
Aeron version id 34The version of the media driver. The driver’s version, composed as major << 16 | minor << 8 | patch; the decoded version is shown beside the value.The version you deployed.A version that differs from this tool’s (the Driver tab and the health line say so).Check that driver, clients and this tool are one release; counters of a newer driver may be shown as unknown.
bytes currently mapped id 35The total number of bytes currently mapped in log buffers, the CnC file, and loss report. Memory the driver has mapped for log buffers, the CnC file and the loss report right now.Grows with the number of publications and images, and falls when they close.Grows without bound, or approaches the limit of the memory filesystem (for example /dev/shm).Check for publications and images that never close on the Streams tab, and free space on the filesystem holding the aeron directory.
retransmitted bytes id 36The minimum bound on the number of bytes re-transmitted as a result of NAKs. A lower bound on the bytes sent again after NAKs.0 or very low.A steady rise: a receiver keeps losing data.Read it with ‘Retransmits sent’ and ‘NAKs received’; compare with ‘Bytes sent’ to see the share of traffic that is repair.
retransmit overflow id 37The number of times that the retransmit pool has been overflowed. Times a retransmit could not be queued because the sender’s retransmit pool was full.0.Any rise: more retransmits were wanted than the sender can handle at once.Look for heavy loss on the path (NAKs received, Loss tab); repair of that loss is being refused.
error frames received id 38The number of error frames received by this driver. Error frames this driver received from a peer.0.Any rise: a peer is rejecting this driver’s traffic.Read the error log on this host and on the peer at the same time.
error frames sent id 39The number of error frames sent by this driver. Error frames this driver sent to a peer.0.Any rise: this driver is rejecting a peer’s traffic.Read this host’s error log for the reason and the peer’s endpoint.
publications revoked id 40The number of publications that have been revoked. Publications that were revoked.0 unless revoking is part of your operation.Any rise you did not cause.Find which client revoked the publication; the Errors tab may say.
publication images revoked id 41The number of publication images that have been revoked. Images on this host that were revoked after their publication was revoked.0 unless revoking is part of your operation.Any rise you did not cause.Read it with ‘publications revoked’ on the publishing host.
images rejected id 42The number of images that have been rejected. Images a subscriber rejected.0 unless rejecting is part of your operation.Any rise you did not cause.Check the subscribing clients and the error log on both hosts.
control protocol version id 43The control protocol between clients and media driver (since 1.49.0). The version of the protocol clients use to talk to this driver.The version of the clients you deployed.A version your clients do not support.Check that clients and driver are one release.
status messages rejected id 44Status messages that are rejected while being outside the send window, i.e. being behind or ahead of the snd-pos by more than one term (since 1.51.0). Status messages the sender ignored because they were more than one term behind or ahead of its sender position.0.Any rise: a receiver is sending status messages for a different or confused position.Check the receivers of the stream and the sender position on the Streams tab; read the error logs on both ends.
native resource agent proxy fails id 45Failed offers to the native resource agent proxy (since 1.51.0). Times the driver could not hand a command to its native resource agent because its queue was full.0.Any rise: that agent is not draining its queue.Check the driver’s other agent cycle times for a stall.

Media driver counters

CounterWhat it counts, and what the value meansNormalWorryingCheck next
pub-lmt type 1The limit as a position in bytes applied to publishers on a session-channel-stream tuple. Publishers will experience back pressure when this position is passed as a means of flow control. A position the producer may not pass yet. Flow control moves it forward as consumers advance.Ahead of the position it limits, by up to the flow-control window.Equal to the position it limits: no room is left and the producer sees back pressure.Find the consumer holding it back: for IPC the slowest subscriber, for a network stream the receivers’ status messages and the sender’s position.
snd-pos type 2The position the Sender has reached for sending data to the media on a session-channel-stream tuple. A byte position in the stream’s log: how far along the stream its owner has got. It only rises.Rises while the stream carries data; the gaps to the stream’s other positions stay small and steady.Flat while pub-pos advances: the sender is not sending (a stalled sender agent or a closed snd-lmt). A gap pub-pos minus snd-pos is the sender backlog.Read pub-pos, snd-pos and snd-lmt together: if snd-pos has reached snd-lmt flow control is holding the sender; if not, check the sender’s cycle time.
rcv-hwm type 3The highest position the Receiver has observed on a session-channel-stream tuple while rebuilding the stream. It is possible the stream is not complete to this point if the stream has experienced loss. A byte position in the stream’s log: how far along the stream its owner has got. It only rises.Equal to rcv-pos, or just ahead of it while packets are in flight.Well ahead of rcv-pos: the receiver has seen data past a gap and is waiting for the missing part (loss).Open the Loss tab for this stream and source; read ‘NAKs sent’ and the sender’s ‘Retransmits sent’; check the network path and the socket receive buffer.
sub-pos type 4The position an individual Subscriber has reached on a session-channel-stream tuple. It is possible to have multiple Subscribers on the same machine tracked by a MediaDriver. How far one subscriber has consumed the stream; each subscription has its own counter.Rises while the stream carries data; the gaps to the stream’s other positions stay small and steady.Far behind pub-pos (IPC) or rcv-hwm (network): a slow consumer that holds the stream’s limit back.The related list gives the lag to the stream’s head (pub-pos for IPC, rcv-hwm for a network image) and names the slowest subscriber; find that client by its owner id and check what it is doing (slow handler, paused thread, full downstream).
rcv-pos type 5The highest position the Receiver has rebuilt up to on a session-channel-stream tuple while rebuilding the stream. The stream is complete up to this point. A byte position in the stream’s log: how far along the stream its owner has got. It only rises.Rises while the stream carries data; the gaps to the stream’s other positions stay small and steady.Stuck below rcv-hwm: a gap is not being repaired.Open the Loss tab and check NAKs and retransmits; a gap that is never filled can end in an image timing out.
snd-channel type 6The status of a send-channel-endpoint represented as a counter value. The status of a channel endpoint: 0 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED.ACTIVE.ERRORED (the error log has the reason), or INITIALIZING that never ends.Read the Errors tab for the reason, then the channel URI (endpoint, interface) in the related stream.
rcv-channel type 7The status of a receive-channel-endpoint represented as a counter value. The status of a channel endpoint: 0 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED.ACTIVE.ERRORED (the error log has the reason), or INITIALIZING that never ends.Read the Errors tab for the reason, then the channel URI (endpoint, interface) in the related stream.
snd-lmt type 9The position the Sender can immediately send up-to on a session-channel-stream tuple. How far the sender may send now; flow control sets it from the receivers’ status messages.Ahead of snd-pos by up to the receiver window.Equal to snd-pos: the sender is held by flow control and publishers will see back pressure.Check the receivers: their status messages and sub-pos; read ‘Sender flow control limits’ and ‘snd-bpe’ for how often it happens.
per-image indicator type 10A counter per Image indicating presence of the congestion control. One exists per image while the image’s congestion control exists; its value is not a measurement.Present while the thing it indicates exists.Absent when the thing it indicates should exist.Use its key to see which image (registration id, session, stream, channel) exists on this host.
client-heartbeat type 11A counter for tracking the last heartbeat of an entity with a given registration id. For a client: the time of its last heartbeat to the driver, in milliseconds since the epoch. The key is the client’s id, which other counters carry as their owner id.Within a fraction of the client liveness timeout of the time of the read.An age that approaches the client liveness timeout (shown on the Driver tab): past it the driver drops the client and what it owns.Use the client id to list the counters it owns (the related list); if the heartbeat is old, check the client process (hung, paused or starved of CPU).
pub-pos type 12The position in bytes a publication has reached appending to the log. Not a real-time value like the others: the conductor updates it for monitoring. A byte position in the stream’s log: how far along the stream its owner has got. It only rises.Rises while the stream carries data; the gaps to the stream’s other positions stay small and steady.Flat while the application says it is publishing, or a limit (pub-lmt) it has caught up with: the publisher is back-pressured.Read pub-pos against pub-lmt for headroom and against the sub-pos or snd-pos below it for backlog (the related list computes both).
snd-bpe type 13Count of back-pressure events (BPE)s a sender has experienced on a stream. A running total since the counter was created; its rate matters more than its size.0, or flat on a stream whose receivers keep up.A rise: the receivers of this stream do not keep up with the sender.See the stream’s rcv and sub positions on the receiving host; read the system counter ‘sender flow control limits’ for the driver-wide count.
local socket address type 14The status of a bind address and port for the local end of a channel. When the value is ACTIVE the key and label hold the socket address and port that is bound. The status of a channel endpoint: 0 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED.ACTIVE.ERRORED (the error log has the reason), or INITIALIZING that never ends.Read the Errors tab for the reason, then the channel URI (endpoint, interface) in the related stream.
resolver neighbors type 15Count of media driver neighbors for name resolution. A current number that goes up and down as things start and stop.What you expect to be running right now.Zero when something should be running, or a number that only grows.Compare it with what is deployed; a number that only grows points at something that never closes.
resolver cache entries type 16Count of entries in the name resolver cache. A current number that goes up and down as things start and stop.What you expect to be running right now.Zero when something should be running, or a number that only grows.Compare it with what is deployed; a number that only grows points at something that never closes.
fc-receivers type 17Count of number of active receivers for flow control strategy. A current number that goes up and down as things start and stop.The number of receivers you expect for the stream.Fewer than expected: a receiver was dropped or never joined; more than expected: an unknown receiver is attached.Compare with the receivers deployed; a missing receiver may have timed out (see ‘status messages’ and image liveness).
mdc-num-dest type 18Count of number of destinations for multi-destination cast channels. A current number that goes up and down as things start and stop.The number of destinations you configured or added.Zero when something should be running, or a number that only grows.Compare with the destinations you expect; a lower number means a destination was removed or never resolved.
snd-naks-received type 19The number of NAK messages received by the Sender. A running total since the counter was created; its rate matters more than its size.0 or very low.A steady rise: receivers of this stream are missing data.Check the receivers’ rcv-hwm against rcv-pos, the system counter ‘retransmits sent’, and the network path.
rcv-naks-sent type 20The number of NAK messages sent by the Receiver. A running total since the counter was created; its rate matters more than its size.0 or very low.A steady rise: this stream is losing packets on the way in.Open the Loss tab for the stream and source; check the NIC, switch and socket receive buffer.
resolver bootstrap neighbor type 21Counter for each bootstrap neighbors used for driver name resolution. Its presence is the information; the value is not a measurement.Present while the thing it indicates exists.Absent when the thing it indicates should exist.Read its label and the related list; it carries no value of its own.

Archive counters

CounterWhat it counts, and what the value meansNormalWorryingCheck next
rec-pos type 100The position a recording has reached when being archived. How many bytes of the stream the archive has recorded into the recording. The key holds the recording id, the session id of the recorded stream and the archive id.Close behind the recorded stream’s position and rising with it.Flat while the stream advances, or a lag to the stream that keeps growing: the recorder is not keeping up or has stopped.The related list gives the recorded stream, the recording and the lag; then check the archive’s recorder max write time, its error count and the free space on the archive volume (Archive dir tab).
archive errors type 101The type id of the counter used for keeping track of the number of errors that have occurred. A count of errors the component has recorded; each one is also in the component’s error log.0.Any rise since the last look.The archive logs its errors in its own error log (mark file), not the driver’s: read it with the archive’s tooling, newest first; the key’s archive id says which archive.
archive control sessions type 102The count of concurrent control sessions. A current number that goes up and down as things start and stop.The number of archive clients you expect to be connected.Zero when something should be running, or a number that only grows.List the clients with the ‘control-session’ counters of the same archive id.
archive max cycle time type 103The max duty cycle time of an archive agent. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Far below the archive’s cycle threshold.At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
archive cycle threshold exceeded type 104The count of cycle time threshold exceeded of an archive agent. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
recorder max write time type 105The max time it took the recorder to write a block of data to the storage. The longest a single write of a block of data to the archive’s storage took.Small and steady for the storage in use.A spike: the storage was slow or stalled, so recording can fall behind (rec-pos lag).Check the archive volume’s latency and free space (Archive dir tab) and the rec-pos lag.
recorder total write bytes type 106The total number of bytes written by the recorder to the storage. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Use its per-second change as the recording write rate; compare with the volume’s capacity and time until full on the Archive dir tab.
recorder total write time type 107The total time the recorder spent writing data to the storage. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Divide its change by the change of ‘recorder total write bytes’ for the time per byte; a rise means the storage is slowing.
replayer max read time type 108The max time it took the replayer to read a block from the storage. The longest a single read of a block of data from the archive’s storage took.Small and steady for the storage in use.A spike: the storage was slow or stalled, so replays can lag.Check the archive volume’s latency; compare with the number of replay sessions.
replayer total read bytes type 109The total number of bytes read by the replayer from the storage. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Mark the view (m) or run with –watch to see its rate over a known time before concluding anything.
replayer total read time type 110The total time the replayer spent reading data from the storage. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Mark the view (m) or run with –watch to see its rate over a known time before concluding anything.
recording sessions type 111The count of active recording sessions. A current number that goes up and down as things start and stop.The number of streams you expect the archive to be recording.Fewer than expected: a recording stopped; check the rec-pos counters.Compare with the rec-pos counters of the same archive id and the Recordings tab.
replay sessions type 112The count of active replay sessions. A current number that goes up and down as things start and stop.The number of replays you expect to be running.Zero when something should be running, or a number that only grows.Compare with the replays your clients should have open.
control-session type 113Tracking Archive clients: the value is the control session id, the label holds the client’s details (since 1.49.0). One per client connected to the archive; the value is its control session id and the key holds the archive id and the same control session id.One per connected archive client.One for a client that has gone away, or none for a client that should be connected.Match the label’s client details to the process; the archive’s control sessions counter gives the total.
persistent subscription state type 114The state of a PersistentSubscription; the label holds the replay and live stream ids and channels. The current state, stored as a code. The decoded name is shown beside the value.LIVE once it has caught up with the live stream; REPLAY while it catches up.FAILED, or a state that is not LIVE or REPLAY for long (an AWAIT state that does not move).A persistent subscription replays from an archive and then joins the live stream: check that the archive is reachable (control sessions), the recording exists, and the channels in the label.
persistent subscription join difference type 115The join difference of a PersistentSubscription. Aeron names it the join difference of a persistent subscription; its source gives no unit or formula for the value.Aeron 1.54.3 does not say.Aeron 1.54.3 does not say.Read it with the persistent subscription’s state and its live joined and left counts.
persistent subscription live left type 116The number of times a PersistentSubscription has left the live stream. A running total since the counter was created; its rate matters more than its size.0, or flat.A rise: the subscription keeps falling behind the live stream and going back to replay.Check that the consumer keeps up with the live stream (sub-pos lag) and the archive’s replay capacity.
persistent subscription live joined type 117The number of times a PersistentSubscription has joined the live stream. A running total since the counter was created; its rate matters more than its size.1 per start; flat afterwards.A count that keeps rising together with ‘live left’.Read it with ‘live left’; repeated joins mean the subscription keeps losing the live stream.

Cluster counters

CounterWhat it counts, and what the value meansNormalWorryingCheck next
consensus module state type 200The consensus module state. The current state, stored as a code. The decoded name is shown beside the value.ACTIVE.INIT that does not end, SUSPENDED you did not ask for, QUITTING or TERMINATING.Check the cluster’s control toggle and election state, and the consensus module’s error count.
cluster node role type 201The cluster node role. The current state, stored as a code. The decoded name is shown beside the value.LEADER on exactly one member, FOLLOWER on the others.CANDIDATE that does not end, or two members that both say LEADER.Read the election state and election count; a member that keeps changing role points at an unstable leader or network between members.
cluster control toggle type 202The control toggle: how an operator asks the cluster for suspend, resume, snapshot, shutdown or abort. The current state, stored as a code. The decoded name is shown beside the value.NEUTRAL: ready to accept a new action.SUSPEND or SHUTDOWN or ABORT that stays set: an operator asked for it.Check who issued the action (ClusterTool) and the consensus module’s state.
cluster commit-pos type 203The commit position. The log position the cluster has committed. It only rises; followers and the services track it.Rises while clients send; the same on every member within a short delay.Flat while clients are sending, or a member far behind the others.Compare the value across members and with the clustered service’s position; check the election state and the leader’s log recording (rec-pos).
cluster recovery state type 204The recovery state for the cluster. Its key holds what the services load on start: the snapshot’s leadership term id, log position and timestamp, the cluster id and each service’s snapshot recording id. The value is not a measurement.Present while the thing it indicates exists.Absent when the thing it indicates should exist.The related list links the snapshot recordings; use them to check the snapshots exist in the archive (Recordings tab).
cluster snapshots type 205The count of snapshots taken. A running total since the counter was created; its rate matters more than its size.Rises by one for each snapshot you took or scheduled.A rate that climbs, or stays above what the load explains.A snapshot that never happens leaves recovery long: check the control toggle and the snapshot duration counters.
cluster election state type 207The election state counter. The current state, stored as a code. The decoded name is shown beside the value.CLOSED once a leader is established.Any state other than CLOSED for long, or a state that keeps changing.Read the election count, node role and the members’ commit positions; a stuck election usually means too few members reachable or logs that cannot be reconciled.
backup state type 208The backup state. The current state, stored as a code. The decoded name is shown beside the value.BACKING_UP between queries.RESET_BACKUP that keeps recurring, or CLOSED when it should run.Check the backup’s error count and its query deadline.
backup live log position type 209The live log position of the backup. How far the backup has recorded the cluster’s live log.Rises while the stream carries data; the gaps to the stream’s other positions stay small and steady.Flat while the cluster commit position advances: the backup is not keeping up.Compare with the cluster’s commit position.
backup query deadline type 210The next query deadline of the backup. A time, in milliseconds since the Unix epoch.Recent: close to the time of the read.A deadline far in the past: the backup is not making its queries.Check the backup’s state and error count.
backup errors type 211The number of errors that have occurred in the backup. A count of errors the component has recorded; each one is also in the component’s error log.0.Any rise since the last look.Read the error log of the component that owns the counter (the Errors tab shows the driver’s), newest entry first.
consensus module errors type 212The consensus module error count. A count of errors the component has recorded; each one is also in the component’s error log.0.Any rise since the last look.Read the error log of the component that owns the counter (the Errors tab shows the driver’s), newest entry first.
cluster client timeouts type 213The number of cluster clients which have been timed out. A running total since the counter was created; its rate matters more than its size.0.Any rise: a cluster client stopped talking to the cluster long enough to be dropped.Find the client process; check its connection to the leader and its keep-alives.
cluster invalid requests type 214The number of invalid requests which the cluster has received. A running total since the counter was created; its rate matters more than its size.0.Any rise: a client sends requests the cluster rejects.Check the consensus module’s error log for the rejected requests.
clustered service errors type 215The clustered service error count. A count of errors the component has recorded; each one is also in the component’s error log.0.Any rise since the last look.Read the error log of the component that owns the counter (the Errors tab shows the driver’s), newest entry first.
consensus module max cycle time type 216The max duty cycle time of the consensus module. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Well below the threshold set for the matching ‘exceeded’ counter.At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
consensus module cycle threshold exceeded type 217The count of cycle time threshold exceeded of the consensus module. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
service max cycle time type 218The max duty cycle time of the service container. The longest time seen, in nanoseconds. It is a maximum, so one stall stays visible.Well below the threshold set for the matching ‘exceeded’ counter.At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
service cycle threshold exceeded type 219The count of cycle time threshold exceeded of the service container. How many work cycles ran longer than the threshold configured for this agent.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
standby snapshots received type 232The count of standby snapshots received. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Mark the view (m) or run with –watch to see its rate over a known time before concluding anything.
node control toggle type 233The counter used for handling node specific operations. The current state, stored as a code. The decoded name is shown beside the value.NEUTRAL: ready to accept a new action.An action that stays set.Check who issued it (ClusterTool) and the consensus module’s state.
snapshot max duration type 234The maximum total snapshot duration. The longest a snapshot of the whole cluster took, in nanoseconds (the counter’s label says ‘in ns’).Well below the threshold set for the matching ‘exceeded’ counter.At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
snapshot duration threshold exceeded type 235The count of times the total snapshot duration has exceeded the threshold. How many snapshots took longer than the configured threshold.0, or flat.Rising: each increment is one stall longer than the threshold.Check the services’ own snapshot durations and the archive’s write times.
service snapshot max duration type 236The maximum snapshot duration for a given clustered service. The longest a snapshot of this clustered service took, in nanoseconds.Well below the threshold set for the matching ‘exceeded’ counter.At or above that threshold, or far above its usual size after a pause.The agent’s thread was held up: look for CPU contention, a blocking call or a pause on that thread, and see the matching ‘exceeded’ counter for how often.
service snapshot threshold exceeded type 237The count of times the snapshot duration of a given clustered service has exceeded the threshold. How many snapshots of this service took longer than the configured threshold.0, or flat.Rising: each increment is one stall longer than the threshold.Line up the times it rises with other symptoms (loss, NAKs, client timeouts); the max counter beside it gives the size of the worst stall.
cluster election count type 238The number of elections that have occurred. A running total since the counter was created; its rate matters more than its size.1 per start; flat afterwards.A count that keeps rising: leadership is unstable.Check the network between members, member pauses (cycle times) and the leader’s logs at the times of the rise.
leadership term id type 239The cluster leadership term id. The id of the current leadership term; it rises with each election.The same on every member.Members that disagree, or a term that keeps rising.Compare across members with the election count.
backup snapshots retrieved type 240The number of snapshots downloaded by the backup. A running total since the counter was created; its rate matters more than its size.Flat, or rising in step with the traffic or work it counts.A rate that climbs, or stays above what the load explains.Mark the view (m) or run with –watch to see its rate over a known time before concluding anything.
cluster-session type 241Tracking Cluster clients (since 1.49.0). One per cluster client session; the value is the cluster session id, and the key holds the cluster id and the same session id.One per connected cluster client.One for a client that has gone away.Match the label’s session details to the client process; compare with ‘cluster client timeouts’.

Counters whose value is a state

CounterValue, state
snd-channel type 60 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED
rcv-channel type 70 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED
local socket address type 140 INITIALIZING, 1 ACTIVE, 2 CLOSING, -1 ERRORED
persistent subscription state type 1140 AWAIT_ARCHIVE_CONNECTION, 1 SEND_LIST_RECORDING_REQUEST, 2 AWAIT_LIST_RECORDING_RESPONSE, 3 SEND_REPLAY_REQUEST, 4 AWAIT_REPLAY_RESPONSE, 5 ADD_REPLAY_SUBSCRIPTION, 6 AWAIT_REPLAY_SUBSCRIPTION, 7 AWAIT_REPLAY_CHANNEL_ENDPOINT, 8 ADD_REQUEST_PUBLICATION, 9 AWAIT_REQUEST_PUBLICATION, 10 SEND_REPLAY_TOKEN_REQUEST, 11 AWAIT_REPLAY_TOKEN, 12 REPLAY, 13 ATTEMPT_SWITCH, 14 ADD_LIVE_SUBSCRIPTION, 15 AWAIT_LIVE, 16 LIVE, 17 FAILED
consensus module state type 2000 INIT, 1 ACTIVE, 2 SUSPENDED, 3 SNAPSHOT, 4 QUITTING, 5 TERMINATING, 6 CLOSED
cluster node role type 2010 FOLLOWER, 1 CANDIDATE, 2 LEADER
cluster control toggle type 2020 INACTIVE, 1 NEUTRAL, 2 SUSPEND, 3 RESUME, 4 SNAPSHOT, 5 SHUTDOWN, 6 ABORT, 7 STANDBY_SNAPSHOT
cluster election state type 2070 INIT, 1 CANVASS, 2 NOMINATE, 3 CANDIDATE_BALLOT, 4 FOLLOWER_BALLOT, 5 LEADER_LOG_REPLICATION, 6 LEADER_REPLAY, 7 LEADER_INIT, 8 LEADER_READY, 9 FOLLOWER_LOG_REPLICATION, 10 FOLLOWER_REPLAY, 11 FOLLOWER_CATCHUP_INIT, 12 FOLLOWER_CATCHUP_AWAIT, 13 FOLLOWER_CATCHUP, 14 FOLLOWER_LOG_INIT, 15 FOLLOWER_LOG_AWAIT, 16 FOLLOWER_READY, 17 CLOSED
backup state type 2080 BACKUP_QUERY, 1 SNAPSHOT_RETRIEVE, 2 LIVE_LOG_RECORD, 3 LIVE_LOG_REPLAY, 4 UPDATE_RECORDING_LOG, 5 BACKING_UP, 6 RESET_BACKUP, 7 CLOSED
node control toggle type 2330 INACTIVE, 1 NEUTRAL, 2 REPLICATE_STANDBY_SNAPSHOT, 3 VALIDATE_RECORDING_LOG

What each key holds

CounterKey
pub-lmt type 1registration id, session id, stream id, channel
snd-pos type 2registration id, session id, stream id, channel
rcv-hwm type 3registration id, session id, stream id, channel
sub-pos type 4registration id, session id, stream id, channel
rcv-pos type 5registration id, session id, stream id, channel
snd-channel type 6channel
rcv-channel type 7channel
snd-lmt type 9registration id, session id, stream id, channel
per-image indicator type 10registration id, session id, stream id, channel
client-heartbeat type 11client registration id
pub-pos type 12registration id, session id, stream id, channel
snd-bpe type 13registration id, session id, stream id, channel
local socket address type 14channel status counter id, local socket address
resolver neighbors type 15not stated in the source
resolver cache entries type 16not stated in the source
fc-receivers type 17registration id, session id, stream id, channel
mdc-num-dest type 18channel
snd-naks-received type 19registration id, session id, stream id, channel
rcv-naks-sent type 20registration id, session id, stream id, channel
resolver bootstrap neighbor type 21not stated in the source
rec-pos type 100recording id, session id, source identity, archive id
archive errors type 101archive id
archive control sessions type 102archive id
archive max cycle time type 103archive id
archive cycle threshold exceeded type 104archive id
recorder max write time type 105archive id
recorder total write bytes type 106archive id
recorder total write time type 107archive id
replayer max read time type 108archive id
replayer total read bytes type 109archive id
replayer total read time type 110archive id
recording sessions type 111archive id
replay sessions type 112archive id
control-session type 113archive id, control session id
persistent subscription state type 114no key
persistent subscription join difference type 115no key
persistent subscription live left type 116no key
persistent subscription live joined type 117no key
consensus module state type 200cluster id
cluster node role type 201cluster id
cluster control toggle type 202cluster id
cluster commit-pos type 203cluster id
cluster recovery state type 204leadership term id, log position, timestamp, cluster id, service snapshot recording ids
cluster snapshots type 205cluster id
cluster election state type 207cluster id
backup state type 208cluster id
backup live log position type 209cluster id
backup query deadline type 210cluster id
backup errors type 211cluster id
consensus module errors type 212cluster id
cluster client timeouts type 213cluster id
cluster invalid requests type 214cluster id
clustered service errors type 215cluster id, service id
consensus module max cycle time type 216cluster id
consensus module cycle threshold exceeded type 217cluster id
service max cycle time type 218cluster id, service id
service cycle threshold exceeded type 219cluster id, service id
standby snapshots received type 232cluster id
node control toggle type 233cluster id
snapshot max duration type 234cluster id
snapshot duration threshold exceeded type 235cluster id
service snapshot max duration type 236cluster id, service id
service snapshot threshold exceeded type 237cluster id, service id
cluster election count type 238cluster id
leadership term id type 239cluster id
backup snapshots retrieved type 240cluster id
cluster-session type 241cluster id, cluster session id

Listed only

AeronCounters.java lists these type ids, and nothing else in Aeron 1.54.3’s Java and C sources uses them: a transport, a cluster module or an application that is not in the tree allocates them. The text is the constant’s own line, and nothing is said about their values.

Type idConstantAreaAeron’s line
50EF_VI_PORT_INFOtransportAeronCounters.java gives only the constant’s name, no description.
51EF_VI_TRANSPORTtransportAeronCounters.java gives only the constant’s name, no description.
52EF_VI_TX_NOBUFStransportAeronCounters.java gives only the constant’s name, no description.
53EF_VI_TX_EAGAINtransportAeronCounters.java gives only the constant’s name, no description.
54EF_VI_TX_ERRORtransportAeronCounters.java gives only the constant’s name, no description.
55EF_VI_RX_DISCARDtransportAeronCounters.java gives only the constant’s name, no description.
56EF_VI_RX_INVALIDtransportAeronCounters.java gives only the constant’s name, no description.
57EF_VI_RX_PKTStransportAeronCounters.java gives only the constant’s name, no description.
58EF_VI_RX_BYTEStransportAeronCounters.java gives only the constant’s name, no description.
59EF_VI_TX_PKTStransportAeronCounters.java gives only the constant’s name, no description.
60EF_VI_TX_BYTEStransportAeronCounters.java gives only the constant’s name, no description.
61VMA_TRANSPORTStransportAeronCounters.java gives only the constant’s name, no description.
62VMA_RX_ZERO_COPY_BYTEStransportAeronCounters.java gives only the constant’s name, no description.
63VMA_RX_DATA_COPY_BYTEStransportAeronCounters.java gives only the constant’s name, no description.
65ATS_TRANSPORTStransportAeronCounters.java gives only the constant’s name, no description.
66ATS_DISCARDS_NON_ATStransportAeronCounters.java gives only the constant’s name, no description.
67ATS_BYTES_ENCRYPTEDtransportAeronCounters.java gives only the constant’s name, no description.
68ATS_BYTES_DECRYPTEDtransportAeronCounters.java gives only the constant’s name, no description.
69ATS_AEAD_ERRORStransportAeronCounters.java gives only the constant’s name, no description.
70ATS_RSA_KEY_UNKNOWNtransportAeronCounters.java gives only the constant’s name, no description.
71ATS_EC_KEY_SIG_ERRORStransportAeronCounters.java gives only the constant’s name, no description.
72ATS_UNICAST_RE_KEYINGStransportAeronCounters.java gives only the constant’s name, no description.
73ATS_UNICAST_RE_KEYING_RSA_KEY_MISMATCHtransportAeronCounters.java gives only the constant’s name, no description.
74ATS_DROPPED_SMtransportAeronCounters.java gives only the constant’s name, no description.
75DPDK_PORT_INFOtransportAeronCounters.java gives only the constant’s name, no description.
76DPDK_TRANSPORTtransportAeronCounters.java gives only the constant’s name, no description.
77DPDK_NOBUFStransportAeronCounters.java gives only the constant’s name, no description.
78DPDK_TX_EAGAINtransportAeronCounters.java gives only the constant’s name, no description.
79DPDK_ERRORtransportAeronCounters.java gives only the constant’s name, no description.
82DPDK_PKTStransportAeronCounters.java gives only the constant’s name, no description.
83DPDK_BYTEStransportAeronCounters.java gives only the constant’s name, no description.
84DPDK_MISSED_PACKETStransportAeronCounters.java gives only the constant’s name, no description.
85DPDK_ARP_MISStransportAeronCounters.java gives only the constant’s name, no description.
86DPDK_RX_SENDER_DISCARDtransportAeronCounters.java gives only the constant’s name, no description.
87DPDK_POLLERtransportAeronCounters.java gives only the constant’s name, no description.
88DPDK_QUEUE_DROP_COUNTtransportAeronCounters.java gives only the constant’s name, no description.
89DPDK_CHECKSUM_FAILUREtransportAeronCounters.java gives only the constant’s name, no description.
90DPDK_FRAGMENTED_PACKETStransportAeronCounters.java gives only the constant’s name, no description.
91DPDK_MEMPOOL_AVAILABLEtransportAeronCounters.java gives only the constant’s name, no description.
92DPDK_EXTENDED_STATStransportAeronCounters.java gives only the constant’s name, no description.
93DPDK_RX_UNSUPPORTED_ETHERNET_TYPEtransportAeronCounters.java gives only the constant’s name, no description.
94DPDK_RX_UNSUPPORTED_PROTOCOLtransportAeronCounters.java gives only the constant’s name, no description.
95DPDK_RX_RECEIVER_DISCARDtransportAeronCounters.java gives only the constant’s name, no description.
220CLUSTER_STANDBY_STATEclusterThe type id of the counter used for the cluster standby state.
221CLUSTER_STANDBY_ERROR_COUNTclusterCounter type id for the clustered service error count (as AeronCounters.java words it).
222CLUSTER_STANDBY_HEARTBEAT_RESPONSE_COUNTclusterCounter type for responses to heartbeat request from the cluster.
223CLUSTER_STANDBY_CONTROL_TOGGLEclusterStandby control toggle type id.
224TRANSITION_MODULE_STATEclusterThe type id of the counter used for transition module state.
226TRANSITION_MODULE_ERROR_COUNTclusterCounter type id for the transition module error count.
227CLUSTER_STANDBY_MAX_CYCLE_TIMEclusterThe max duty cycle time of the cluster standby.
228CLUSTER_STANDBY_CYCLE_TIME_THRESHOLD_EXCEEDEDclusterThe count of cycle time threshold exceeded of the cluster standby.
229TRANSITION_MODULE_MAX_CYCLE_TIMEclusterThe max duty cycle time of the transition module.
230TRANSITION_MODULE_CYCLE_TIME_THRESHOLD_EXCEEDEDclusterThe count of cycle time threshold exceeded of the transition module.
231CLUSTER_STANDBY_SOURCE_MEMBER_IDclusterMakes visible the member id the cluster standby currently uses as a source for the cluster log.
300SELECTOR_CLIENTS_COUNTERapplicationAeronCounters.java gives only the constant’s name, no description.
301SELECTOR_SUBSCRIPTIONS_COUNTERapplicationAeronCounters.java gives only the constant’s name, no description.
302SELECTOR_MAX_CYCLE_TIMEapplicationAeronCounters.java gives only the constant’s name, no description.
303SELECTOR_CYCLE_TIME_THRESHOLD_EXCEEDEDapplicationAeronCounters.java gives only the constant’s name, no description.
500SEQUENCER_INDEX_COUNTERapplicationSequencer index.
501SEQUENCER_GROUP_HWM_COUNTERapplicationApplication group last message.
502SEQUENCER_SESSION_GREATEST_MESSAGE_ID_COUNTERapplicationSession last message.
503SEQUENCER_SESSION_MESSAGES_COUNTERapplicationSession messages.
504SEQUENCER_SESSION_GREATEST_MESSAGE_TIMESTAMP_COUNTERapplicationSession last message timestamp.
505SEQUENCER_CLIENT_SNAPSHOT_ID_COUNTERapplicationThe next snapshot id.
507SEQUENCER_APPLICATION_SEQUENCE_INDEX_COUNTERapplicationSequence index.
508SEQUENCER_APPLICATION_STATE_COUNTERapplicationApplication state.
509SEQUENCER_APPLICATION_ERROR_COUNTapplicationError count.
510SEQUENCER_APPLICATION_MAX_SERVICE_TIMEapplicationMax service time.
511SEQUENCER_APPLICATION_SERVICE_TIME_THRESHOLD_EXCEEDED_COUNTapplicationThe number of times the service time threshold was exceeded.
512SEQUENCER_APPLICATION_INTERVAL_SERVICE_TIMEapplicationThe total service time during the last interval.
513SEQUENCER_APPLICATION_INTERVAL_MAX_SERVICE_TIMEapplicationThe maximum individual service time during the last interval.
514SEQUENCER_APPLICATION_INTERVAL_TOTAL_INVOCATIONSapplicationThe total number of invocations during the last interval.
515SEQUENCER_APPLICATION_SNAPSHOT_LOAD_TIMEapplicationThe load time, in milliseconds, of a snapshot.
516SEQUENCER_APPLICATION_SNAPSHOT_STORE_TIMEapplicationThe store time, in milliseconds, of a snapshot.
517SEQUENCER_APPLICATION_TAKE_SNAPSHOT_FAILURESapplicationThe number of ‘take snapshot’ failures.
518SEQUENCER_APPLICATION_TAKE_SNAPSHOT_COUNTapplicationThe number of ‘take snapshot’ instances.
519SEQUENCER_APPLICATION_SESSION_IDapplicationThe application service’s session with the sequencer.
520SEQUENCER_REPLAY_INDEX_MIN_SEQUENCE_INDEX_COUNTERapplicationThe replay index’s minimum sequence index.
521SEQUENCER_REPLAY_INDEX_MIN_SEQUENCE_LOG_POSITION_COUNTERapplicationThe replay index’s minimum log position.
522SEQUENCER_REPLAY_INDEX_MAX_SEQUENCE_INDEX_COUNTERapplicationThe replay index’s maximum sequence index.
523SEQUENCER_REPLAY_INDEX_MAX_SEQUENCE_LOG_POSITION_COUNTERapplicationThe replay index’s maximum log position.
524SEQUENCER_REPLAY_INDEX_INITIAL_SEQUENCE_INDEX_COUNTERapplicationThe replay index’s initial sequence index.
525SEQUENCER_REPLAY_INDEX_INITIAL_SEQUENCE_LOG_POSITION_COUNTERapplicationThe replay index’s initial log position.
526SEQUENCER_APPLICATION_GREATEST_COMMITTED_MESSAGE_ID_COUNTERapplicationThe greatest committed message id that has been communicated by the Sequencer to the Application.
531SEQUENCER_REPLAY_SERVICE_SESSION_COUNTapplicationThe number of active replay sessions within the replay service.
535SEQUENCER_REPLAY_SERVICE_INDEXED_TERM_COUNTapplicationThe number of terms indexed by the cache for the replay service.
536SEQUENCER_REPLAY_SERVICE_TOTAL_TERM_COUNTapplicationThe total number of terms known to the cache in the replay service.
537SEQUENCER_REPLAY_SERVICE_REPLAY_JOBapplicationThe replay job.
538SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_STORE_OPERATIONS_COUNTERapplicationThe number of active snapshot store operations for the snapshot service.
539SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_LOAD_OPERATIONS_COUNTERapplicationThe number of active snapshot load operations for the snapshot service.
540SEQUENCER_SNAPSHOT_SERVICE_REPLICATING_COUNTapplicationThe number of active snapshot replication operations for the snapshot service.
541SEQUENCER_APPLICATION_LAST_READ_TIMESTAMP_COUNTERapplicationThe log timestamp of the last message processed by the Application.
542SEQUENCER_REPLAY_CLIENT_LOG_REPLAY_SEQUENCE_INDEXapplicationThe sequence index read by the log replay client.
543SEQUENCER_REPLAY_SERVICE_STATEapplicationThe state of the replay service.
544SEQUENCER_SNAPSHOT_SERVICE_STATEapplicationThe state of the snapshot service.
545SEQUENCER_REPLAY_SERVICE_MAX_CYCLE_TIME_COUNTERapplicationThe max duty cycle time of the replay-service agent.
546SEQUENCER_REPLAY_SERVICE_CYCLE_TIME_THRESHOLD_EXCEEDEDapplicationThe count of cycle time threshold exceeded of a replay-service agent.
547SEQUENCER_SNAPSHOT_SERVICE_MAX_CYCLE_TIME_COUNTERapplicationThe max duty cycle time of the snapshot-service agent.
548SEQUENCER_SNAPSHOT_SERVICE_CYCLE_TIME_THRESHOLD_EXCEEDEDapplicationThe count of cycle time threshold exceeded of a snapshot-service agent.
549SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_SESSIONS_COUNTERapplicationThe number of currently connected sessions on the snapshot service.
550SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_ADMIN_OPERATIONS_COUNTERapplicationThe number of active snapshot admin operations (delete / invalidate / revalidate) for the snapshot service.
551SEQUENCER_SNAPSHOT_SERVICE_QUEUED_OPERATIONSapplicationThe number of operations queued but not yet started across all sessions on the snapshot service.
552SEQUENCER_SNAPSHOT_SERVICE_STORE_ERROR_COUNTapplicationThe number of terminal store-operation errors on the snapshot service.
553SEQUENCER_SNAPSHOT_SERVICE_LOAD_ERROR_COUNTapplicationThe number of terminal load-operation errors on the snapshot service.
554SEQUENCER_SNAPSHOT_SERVICE_LIST_ERROR_COUNTapplicationThe number of terminal list-operation errors on the snapshot service.
555SEQUENCER_SNAPSHOT_SERVICE_ADMIN_ERROR_COUNTapplicationThe number of terminal admin-operation (delete / invalidate / revalidate) errors on the snapshot service.
556SEQUENCER_SNAPSHOT_SERVICE_STORAGE_MODULE_ERROR_COUNTapplicationThe number of storage-module errors surfaced to the snapshot service.
557SEQUENCER_APPLICATION_SNAPSHOT_LAST_STORED_SEQUENCE_INDEXapplicationThe sequence index of the last snapshot stored by the application.
558SEQUENCER_APPLICATION_SNAPSHOT_LAST_LOADED_SEQUENCE_INDEXapplicationThe sequence index of the last snapshot loaded by the application.
559SEQUENCER_APPLICATION_SNAPSHOT_ACTIVITY_STATEapplicationThe application’s current snapshot activity state (0 = idle, 1 = storing, 2 = loading).
560SEQUENCER_APPLICATION_SNAPSHOT_LOAD_ERROR_COUNTapplicationThe number of snapshot load failures observed by the application.
561SEQUENCER_SNAPSHOT_SERVICE_TOTAL_STORE_OPERATIONS_COUNTERapplicationThe total number of snapshot store operations requested on the snapshot service.
562SEQUENCER_SNAPSHOT_SERVICE_TOTAL_LOAD_OPERATIONS_COUNTERapplicationThe total number of snapshot load operations requested on the snapshot service.
563SEQUENCER_SNAPSHOT_SERVICE_TOTAL_LIST_OPERATIONS_COUNTERapplicationThe total number of snapshot list operations requested on the snapshot service.
564SEQUENCER_SNAPSHOT_SERVICE_TOTAL_FIND_LATEST_OPERATIONS_COUNTERapplicationThe total number of snapshot find-latest operations requested on the snapshot service.
565SEQUENCER_SNAPSHOT_SERVICE_TOTAL_ADMIN_OPERATIONS_COUNTERapplicationThe total number of snapshot admin operations (delete / invalidate / revalidate) requested on the snapshot service.
566SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_LIST_OPERATIONS_COUNTERapplicationThe number of active snapshot list operations for the snapshot service.
567SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_FIND_LATEST_OPERATIONS_COUNTERapplicationThe number of active snapshot find-latest operations for the snapshot service.
568SEQUENCER_SNAPSHOT_SERVICE_ACTIVE_DESCRIBE_OPERATIONS_COUNTERapplicationThe number of active describe operations in the snapshot service.
569SEQUENCER_SNAPSHOT_SERVICE_TOTAL_DESCRIBE_OPERATIONS_COUNTERapplicationThe total number of describe operations in the snapshot service.
570SEQUENCER_SNAPSHOT_SERVICE_DESCRIBE_ERROR_COUNTapplicationThe number of terminal describe-operation errors on the snapshot service.

Why the viewer is passive

A program that subscribes to a stream only to look at it is still a subscriber, and Aeron makes publishers wait for their subscribers:

StreamWhat holds the publisher back
IPC publicationits limit is the slowest subscriber’s position plus the term window
Network publication with a spyspies count in the publisher’s limit, as the sender does
Image received from another hostthe slowest subscriber sets the status message, so the remote sender’s window

So a viewer that subscribes and then stops reading (a paused screen, a pipe nobody reads) holds the publisher at its limit. tether=false only bounds the hold: an untethered subscriber that falls behind still counts until the driver’s untethered window timeout passes.

ergo-aeron does not subscribe. Its tap reads the stream’s log file, the file the driver itself writes the stream into, and the counters that say how far the stream has gone:

publisher writes the log: publications/<id>.logbuffer←publisher limit = slowest subscriber position + term window
a subscriber that keeps up→subscriber position counter (type 4)→counted in the limit
a viewer that subscribes, then stops reading→its position counter stops→the limit stops: the publisher is back-pressured
ergo-aeron's tap reads the log file and the head, limit and subscriber position counters→no client, no subscription, no counter→nothing for the driver to wait for; a tap that falls behind skips what the driver has cleaned

What the tap reads

StreamLog fileRead up to
IPC or network publication on this driverpublications/<registration id>.logbufferthe publisher position counter (type 12)
Image this driver receivesimages/<registration id>.logbufferthe receiver position counter (type 5), the end of the data with no gap

The registration id is in the counter’s key, and the log’s own metadata names it again; the tap checks that they agree. Each frame header’s term id and term offset must be the ones its position implies, so a frame the publisher has since written over is never taken for the one the tap wanted.

What it costs: messages can be missed

The driver cleans a log behind its slowest reader, and the tap is not one of its readers:

StreamCleaned up to
IPC publicationthe slowest subscriber’s position
Network publicationone term behind the sender and its spies
Imageone term behind the slowest subscriber

So a tap that falls behind loses messages: it skips forward to data that is still there and counts the bytes it skipped (skipped on the Messages tab’s status line; fell behind: skipped N bytes on standard error from the command line). A fragmented message cut by a skip is counted as cut. On IPC the slack is smallest. The driver cleans when the slowest subscriber has moved an eighth of the term window past the last clean, and cleans up to that subscriber before it raises the publisher limit; so once the slowest subscriber is that far past limit - window, the tap takes the subscriber’s own position as the floor and drops what lies behind it. It reads every millisecond on a thread of its own; a messages screen that draws slowly drops messages from its own queue instead (dropped), never from the stream.

After each copy the tap reads the floor again and drops the frames below it, and it reads each frame’s header again after its body. A frame that fails either check is skipped, never shown. Not covered: an untethered IPC subscriber that the driver has set resting is left out of the driver’s own slowest position but not out of the tap’s, so while one rests the tap can trust a frame the driver is already cleaning.

A stream that joined mid-term (an image of a stream already running) starts with zeros the driver never wrote: the tap starts at its first frame and counts nothing as skipped. A driver restarted in the same directory ends the tap (the stream has closed).

In a pod

The tap needs the driver’s aeron directory mounted readable, as the other tabs do: cnc.dat, and the publications and images folders beside it. It needs no write access and starts no Aeron client, so the volume can be mounted read-only.

Attached or embedded

ergo-aeron reaches a driver in one of two ways. Attached mode is the default and the only passive one.

Attached (default)Embedded (--embedded)
What it isreads an existing driver’s files; no Aeron client, no subscriptionstarts a media driver of the tool’s own, in a new directory, plus a client on it
Streams it showsevery stream that driver carries, picked from the Streams taba stream you name by channel URI and stream id, joined as a receiver: multi-destination, multicast, or a unicast one sent to this host (its publisher then has this tool as its only receiver, so the tool paces it: read such a stream attached if that matters)
Stats tabsthat driverthe tool’s own driver (own driver on the top line), unless --aeron-dir names another
Effect on publishersnone (why)it is a real receiver; see the guards below
Good forthe host or pod where the driver runsa machine with no driver on the stream’s network

ergo-aeron is the installed binary (Install).

Embedded mode

Embedded mode never starts by itself: with no live driver, attached mode says so and names --embedded. Join a stream with:

ergo-aeron --embedded messages --stream 2002 --follow \
    --channel 'aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457' \
    --schema sbe/tests/fixtures/schemas/car.xml

or open the screen on it with ergo-aeron --embedded --channel URI --stream N. Standard error names the driver’s directory and says [LIVE RECEIVER]; the screen keeps [LIVE RECEIVER] on its top line. A receiver has nothing retained, so messages --channel needs --follow. The subscription is polled on a thread of its own into a bounded queue: a slow or stalled pipe loses messages (dropped N messages on standard error), never the subscription’s pace. When the queue is full it is the newest batch that is dropped, not the oldest.

Both at once is allowed: with --aeron-dir DIR --embedded the stats tabs read DIR passively (the top line names it, not own driver) while channels are joined through the tool’s own driver.

The driver’s directory is new for each run: --embedded-dir DIR, which must not exist (its parent must), or by default a fresh one beside Aeron’s default directory. It is created here and nowhere else:

  • a directory that exists is refused, empty or not, and left as it is; one that holds a live driver is refused saying so;
  • the directory and the driver’s settings are set explicitly, so no AERON_DIR or AERON_DIR_DELETE_ON_START in the environment can aim it at another driver;
  • it is removed on exit, on SIGINT, SIGTERM and SIGHUP, on a closed pipe and after a failed start, but never while a live driver is in it. A process killed with SIGKILL leaves it behind, as can one ended because it was still running 5 seconds after a signal, stuck or not.

The driver runs in shared threading mode with the sleep-ns idle strategy (1 ms), so it sleeps when idle and needs no CPU of its own; its own logs use 64 KiB sparse terms. Other AERON_* settings (a network interface, socket buffers) come from the environment as usual, except the ones that decide how the viewer talks to the publisher or how long a stalled stream stays silent: the receiver group tag and group consideration, the reliable, tether and rejoin defaults, the status message, image liveness and untethered timeouts are set by the tool over the environment, and an AERON_CONGESTIONCONTROL_SUPPLIER other than Aeron’s default or static refuses the start (cubic congestion control sends round-trip probes to the publisher).

In Kubernetes the directory lives in the pod, not on the node: give it a writable memory-backed emptyDir (--embedded-dir under it), and make sure the pod can reach the stream over the network (the pod network or hostNetwork, and the UDP port of its own endpoint). The tool’s own driver belongs to the pod that runs it; it reads the pod’s media driver only if told (--aeron-dir, attached).

The guards

Every viewer subscription gets these options, whatever the typed URI says:

OptionWhat it does for the viewer
reliable=falsea gap is filled locally and its bytes are counted as skipped; no NAK asks the publisher to resend
tether=falsestated plainly; it does not make its driver drop a lagging viewer (see below)
untethered-window-limit-timeout=500ms, untethered-resting-timeout=1sthe same: they never act on the viewer (Aeron’s defaults are 5 s and 10 s)
group=falsestated plainly; with reliable=false it changes nothing on the wire
no gtag, no group tag on its driver, rejoin left at its defaultnever a member of a tagged flow-control group, even with AERON_RECEIVER_GROUP_TAG in the environment
no ccno cubic congestion control, which would send round-trip probes to the publisher
no rcv-wndthe receiver window is the driver’s 128 KiB (at most half the term), the one the viewer’s own leave is a share of
session-id, with --session Sone publisher instead of every one on the stream

There is no driver backstop. Aeron’s untether (tether=false and the untethered timeouts) measures a subscriber’s lag against the furthest subscriber of the same image, and the viewer is the only one on its driver, so its driver never drops it. The viewer’s own leave is the only guard, and it leaves the stream when:

  • it is behind what its driver has ready to read by more than half the stream’s receiver window (the driver’s 128 KiB, never more than half the term, so 64 KiB on terms of 256 KiB and up) on three checks in a row, 10 ms apart: a viewer a busy machine kept off the CPU for a moment catches up on its next reads and stays;
  • it is past three quarters of the window, which it leaves on the first check;
  • its driver counts frames dropped beyond its accept limit (the system counter Flow control over runs) since the viewer last joined. A receiver takes a frame only up to its last status message plus half the term; past that it drops every frame, heartbeats too, and the stream stays silent until the image times out (10 s) while the viewer’s lag reads 0, so the counter is the only sign. The status message trails the viewer’s reads, so a burst arriving just after the viewer catches up can be dropped: it then leaves and rejoins 1 s later, even if it was inside its lag bound.

It leaves without reading the backlog, says why (on standard error, and on the Messages tab’s status line), and rejoins at the live position a second later. If its driver is still closing the endpoint it left and says to retry, it tries again 100 ms later, at most 20 times; after that the error, with the driver’s words, ends the stream.

A gap from loss is not lag, so the viewer does not leave for it. Its driver fills the gap with padding, and the viewer adds the bytes its driver’s loss report records to skipped (lost: skipped N bytes ... on standard error, skipped on the Messages tab’s status line). That covers a datagram lost in the network and one the kernel dropped because the viewer’s socket buffer was full, which a stall of its driver’s thread of about ten milliseconds can cause. Known limitation: over UDP the embedded viewer can lose data at a term end.

A fatal error from Aeron’s client (the driver went away, or the process was suspended for longer than the driver timeout) ends the stream the same way, through the next read, so the directory is removed and the terminal restored; Aeron’s own handler would have exited the process. So does a failure of the client’s own conductor (an image that cannot be mapped, say), and a UDP receive channel whose status is errored (checked every 10 ms; Aeron’s C driver never sets it, the Java driver does). A join the driver refuses (an invalid channel, no storage space) is the error of the join itself, before any stream. Other client errors (a full buffer to the driver, say) are counted and do not end it. The count of dropped frames is one counter for the whole driver, so there is one viewer per embedded driver: a second is refused with a clear error.

typed:   aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457
joined:  aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457|reliable=false|tether=false|group=false|untethered-window-limit-timeout=500ms|untethered-resting-timeout=1s

typed:   aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457|reliable=true|tether=true|gtag=7
joined:  aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457|reliable=false|tether=false|group=false|untethered-window-limit-timeout=500ms|untethered-resting-timeout=1s

typed:   aeron:udp?endpoint=224.0.1.1:40456|interface=192.0.2.10|fc=min
refused: fc=min: under min flow control any receiver can hold the publisher, so embedded mode refuses to join (attach to the publisher's driver instead)

typed:   aeron:ipc
refused: an IPC stream belongs to its own driver; read it attached (--aeron-dir), which is passive

Under Aeron’s default flow control for multi-destination and multicast streams (max) the sender follows its fastest receiver: the viewer cannot hold a publisher that has a faster receiver, but a viewer that is the only receiver of the stream paces it, and the strategy goes on counting it until its receiver timeout (5 s by default) after it leaves. The viewer cannot see how many receivers a publisher has, so this is not detected; join such a stream attached (passive) when the publisher must not wait. Under tagged flow control only receivers with the group’s tag count, so the viewer cannot hold such a publisher (it sends no tag, even with AERON_RECEIVER_GROUP_TAG in the environment). Do not join a stream whose publisher uses fc=min: then every receiver counts, and one that leaves is still counted until the strategy’s receiver timeout (5 s by default). The viewer cannot see the publisher’s setting, so a typed URI with fc=min is refused and the screen shows LIVE RECEIVER throughout; a fc=min publisher the URI does not mention is not detected.

An IPC stream and a spy belong to the driver they run on, so they are refused here: read them attached, which is passive.

History

ergo-aeron remembers what it was used with, so it is easier to open again:

RememberedUsed for
aeron directories that were read (attached)history
a stream of an attached driver, or a channel and stream joined embedded, with the schema sources loaded with itthe screen’s picker (o or F7), which reopens it with those schemas; messages without --schema offers them on standard error
schema sources: file paths, directories and URLs, never the schema textthe picker loads one (a URL only at start, with --schema); a path no longer there shows as schema (missing) and is skipped when a stream’s schemas are reloaded
archive directories (--archive-dir) and archive control channels with their stream (--control)history; a control channel is kept only when every parameter is one of Aeron’s own, so a value typed where a credential might go is never written
kind              value                                                        stream  schemas                              last used ms
channel           aeron:udp?endpoint=192.0.2.10:40456|control=192.0.2.1:40457    2002  sbe/tests/fixtures/schemas/car.xml  1764400002000
stream            /dev/shm/aeron                                                 1001  sbe/tests/fixtures/schemas/car.xml  1764400001000
schema            sbe/tests/fixtures/schemas/car.xml                                                                       1764400001000
schema (missing)  schemas/old.xml                                                                                          1764400000500
aeron-dir         /dev/shm/aeron                                                                                           1764400000000

The file is $XDG_STATE_HOME/ergo-aeron/history.json, else ~/.local/state/ergo-aeron/history.json (on macOS too), written owner-only (the directory 0700, the file 0600). It keeps the newest 200 entries and 64 schema sources per stream. It holds names only: no message, and no URL with user information, a query or a fragment, where a credential would sit. A channel URI is kept as typed (no Aeron 1.54 channel parameter is a credential); an archive control channel only when every parameter is one of Aeron’s own, so a value typed under any other key is never written.

Each run writes the whole file through a temporary file of its own name, renamed into place, so two runs saving at once never leave a torn file. The last one to save wins: it writes what it read at its start plus what it did, so a long screen session that ends after a shorter command forgets that command’s entries (and history clear run meanwhile).

Read back, the file is untrusted: one that is corrupt, larger than 1 MiB or unreadable is ignored with one notice on standard error, and a directory that cannot be written turns history off with one notice. Neither stops the command. --no-history reads and writes nothing; history lists the entries (table or JSON lines) and history clear forgets them.

Archive tabs

ergo-aeron reads an Aeron Archive two ways, apart or together:

SourceFlagTab and subcommandsWhat it touches
Online--control URI (--control-stream, --control-response)Recordings and Payload; recordings, recording ID, replay IDa control session on the archive, read requests only, through an Aeron client on the attached driver (or the tool’s own with --embedded); a replay also subscribes to what the archive sends back
Offline--archive-dir DIRArchive dir; archive-dir ...the directory’s files, opened read-only; the archive may be running or stopped
Countersthe attached driverrecording-lag, the Recordings tab’s lag column, and the Recordings tab itself when the counters show an archivethe archive’s driver’s cnc.dat, as the other tabs read it

The archive tabs appear only with their source. A missing driver does not stop the Archive dir tab from opening, and a missing archive does not stop the driver tabs. Nothing here writes: no archive action is in writer mode yet, and every command below is in the read list that the write gate’s test walks.

An archive seen in the counters

In the terminal UI, without --control, the tool looks at the attached driver’s counters for an archive’s own (type ids 100 to 113: recording positions, error and cycle counters, control sessions). When there is one, the top line says archive N detected and the Recordings tab appears with what the counters hold and nothing else: recording id, archive, stream, session, recording position, the stream’s position and the lag. Only recordings being written have a counter, so stopped ones are not listed. No client is added to the driver.

c (or F12) opens the control session, on aeron:ipc and the --control-stream id (10 by default): the counters are on this driver, so the archive records through it. c again asks for another control channel, typed and then Enter (Esc cancels). The tool never connects by itself. A session that fails keeps the counter rows on screen and shows the reason.

With --aeron-dir and --embedded together the session goes through the tool’s own driver, which an aeron:ipc channel cannot reach, so c asks for the channel at once. --control keeps its meaning: the session is opened at start and the counters-only view is not used.

Online: the control session

ergo-aeron --aeron-dir /dev/shm/aeron --control 'aeron:udp?endpoint=archive-host:8010' recordings
ergo-aeron --aeron-dir /dev/shm/aeron --control aeron:ipc recording 3

recordings lists what the archive’s catalogue holds (--channel TEXT --stream N filters, --from and --count page; at most 10000 per request) with the same columns as the offline listing below. When --count (1000 by default) leaves recordings out, a line on standard error says how many and which id to give --from for the next page (or more when the request itself was full). recording ID prints one descriptor with its four positions: start, stop (- while recording), recording position (- when not recording) and the highest position recorded.

The session is not passive. Connecting adds an Aeron client to the driver it goes through and a control session to the archive, whose responses come back on a subscription addressed to this tool alone (--control-response, by default aeron:ipc for an IPC control channel, else aeron:udp?endpoint=localhost:0, Aeron’s own default). The requests are the listings, the position queries and, for a payload, the replay; the java lane’s tests read the archive’s control stream while the tool runs and fail on any other request.

That response subscription is the one subscription of the tool that does not carry the viewer’s guards (reliable=false, tether=false, the short untethered timeouts, Attached or embedded). The guards exist so that a receiver joining a stream other receivers share cannot slow its publisher. Nobody shares this stream: the archive sends the responses to this session only, and a response lost to reliable=false would fail the very request that asked for it. The tool says so on the channel (tether=true, and reliable=true on UDP, unless --control-response already says): its own driver in embedded mode defaults every subscription to the guards. A replay’s subscription says the same.

Which driver the client goes through:

GivenThe session goes through
--aeron-dirthat driver, which so gains a client
--embeddedthe tool’s own driver
boththe tool’s own driver: the driver tabs and recording-lag still read --aeron-dir, which gains no client

An aeron:ipc control channel exists only inside the archive’s own driver, so with --embedded it is refused before anything starts: name the driver with --aeron-dir and leave --embedded out. Reach a remote archive through --embedded and a UDP control channel, and give --control-response 'aeron:udp?endpoint=THIS-HOST:0' with an address of this host that the archive can reach: the default response channel, localhost:0, would have the archive send its responses to itself, and the connection would time out.

The Recordings tab does not list the archive on every refresh. Each listing (at most 10000 recordings) is answered by the archive’s conductor, which with shared threading is also its recorder, so the tab lists everything once when it opens and once a minute after that. Between those it asks only for the recordings after the highest id it knows and, one request each, for the recordings that have not stopped yet. It waits at least one second between refreshes whatever --interval says. A recording deleted from the archive stays in the tab for up to a minute. Past 10000 recordings the tab shows the first 10000 and says so in its status line; recordings --from ID lists the rest.

The tool sends no credentials, and has no way to be given any: an archive that authenticates its clients refuses the session. A control channel with a parameter that is not one of Aeron’s own (where a credential might have been typed) has that value shown as *** in every message, and is never kept in the history.

Building without the control reader

The control reader is the cargo feature archive, on by default. It is the one part of the crate that needs rusteron’s archive client, whose build runs Aeron’s Gradle and so needs a JDK 17 or newer. Without it (--no-default-features --features cli,tui,static) the crate builds with no JDK; recordings, recording and the Recordings tab’s --control then say built without the archive control reader and exit 2 (the Recordings tab shows the same line), and replay says the same. archive-dir, recording-lag and every driver tab work in both builds.

Payload: replaying a recording

ergo-aeron --control aeron:ipc replay 3 --schema schemas/
ergo-aeron --control aeron:ipc replay 3 --from 4096 --length 1048576 --format raw > part.bin
ergo-aeron --control aeron:ipc replay 3 --follow --format compact

replay ID asks the archive to send the recording back to the tool and prints its messages as messages prints a stream’s: the same formats, --schema, --interpret and --converters. Without --follow it prints what the recording holds when it starts, and exits. With --follow it goes on as the recording grows and exits when the recording stops. --from POSITION must be where a frame starts (a position replay or archive-dir dump has printed); --length BYTES stops after that much of the recording. A position outside the recording, or one inside a frame, is refused with the reason (exit status 2). So is a replay cut off: the driver closing the tool’s client, or the replay ending before the length asked or, with --follow, while the recording goes on. Ctrl-C or SIGTERM ends --follow cleanly.

In the terminal UI, w (or F4) on a recording of the Recordings tab replays it onto the Payload tab: from the start of the term that holds the byte 1 MiB before the end (only a term’s start is known to be a frame), then live while it records. The tab has what the Messages tab has: the list filter (/), the preview with its regular expression search (Enter, then /), the counts per message type, i and Space. It keeps the newest 5000 messages, and the filter searches those. w on another recording starts again.

A replay is a read: the archive reads its files and sends them, and no recording changes. It does cost the archive that work. What it touches:

WhatHow
Sessioneach replay opens its own client and control session, beside the listing’s, and closes them when it ends
Where it is sentthe control response channel (--control-response), on stream 1163020033, to this tool alone
Loses nothingthe subscription asks for tether=true, and reliable=true on UDP, unless --control-response already says otherwise
Ids shownthe recording’s stream and session, not the replay’s
On an aeron:ipc or fixed-port channelthe tool picks the replay’s session id (replacing any session-id given) and subscribes to it before asking, so it joins no other publication on that channel and stream and cannot hold one back
On a UDP channel with port 0the tool’s driver picks a port of its own, and the replay is asked for there
A slow readerslows the replay, which loses nothing (a live stream’s tap drops instead)
Its endthe archive ends it: at the length asked, when the recording stops, or when the tool’s subscription closes. The tool sends no stop request

A control-mode=response channel is not supported for a replay. A remote archive needs --control-response with an address it can reach, as the listings do.

Recording lag

Each active recording has a recording position counter in the driver the archive records through. recording-lag reads those counters with the stream’s own position on the same driver (its publisher’s position, or for a stream received from another host its receiver’s high-water mark), so it needs no archive session at all:

             archive             recording       stream      session      counter              recorded            source pos  lag
                  42                     7         3001           88           71               1277952               1310720  32768

lag is the stream’s position minus the recording’s, never below 0; - when this driver neither publishes nor receives the stream. The Recordings tab shows the same as its rec pos and lag columns when the attached driver is the archive’s. Two archives recording through one driver can each have a recording 3, so the counter’s label names its archive, and the tab and recording ID match on the archive and the recording together.

The recording is matched to its stream by the channel in the counter’s label (rec-pos: <recording id> <session id> <stream id> <channel> - archiveId=<n>), not by the session id and the stream id alone: two publications can share those on different channels, and each recording keeps its own numbers. A long channel is cut short by the counter’s label buffer, so a label that names the start of one is matched on that; when it could name more than one of the driver’s streams, the lag is - and the recording’s detail says why.

Offline: the archive directory

archive-dir with no action prints the catalogue header, the mark file and every entry:

field               value
catalogue           fixture/archive.catalog
catalogue version   3.1.0
catalogue capacity  65536
next recording id   3
mark file           fixture/archive-mark.dat
archive version     3.1.0
pid                 82185
archive id          42
started (UTC)       2026-11-30 23:55:04.908
activity (UTC)      -
control              stream 10
local control       aeron:ipc?term-length=64k stream 10
events               stream 30
aeron dir           aeron

           recording  state            stream      session             start pos              stop pos                 bytes  started (UTC)            stopped (UTC)            source                    channel
                   0  VALID              1001   1411926094                     0                   352                   352  2026-11-30 23:55:05.466  2026-11-30 23:55:05.490  aeron:ipc                 aeron:ipc
                   1  INVALID            1002   1411926095                     0                  3104                  3104  2026-11-30 23:55:05.507  2026-11-30 23:55:05.538  aeron:ipc                 aeron:ipc
                   2  VALID              1003   1411926096                     0                     0                     0  2026-11-30 23:55:05.568  2026-11-30 23:55:05.588  aeron:ipc                 aeron:ipc

The actions are ArchiveTool’s read commands:

archive-dir ...ArchiveToolPrints
describe [ID]describe [ID]the VALID entries, or entry ID in any state
describe-alldescribe-allevery entry with its state
count-entriescount-entrieshow many entries are VALID
capacitythe capacity line of describethe catalogue’s length in bytes
pidpidthe archive’s pid, from its mark file
errorserrorsthe archive’s own error log (ergo-aeron errors --aeron-dir reads the driver’s)
dump [--limit N] [--dump BYTES]dump [N]each entry, then each VALID recording’s frames from its segment files
verify [ID] [-a]verify [ID] [-a]the same checks, reporting only
segmentseach segment file, its length and the bytes allocated to it
disk [--between MS]disk use and time until full (below)

--format json prints one object per entry or frame. dump prints frames as they are read; payloads are hex, cut at --dump bytes (65536 by default):

           recording  state            stream      session             start pos              stop pos                 bytes  started (UTC)            stopped (UTC)            source                    channel
                   0  VALID              1001   1411926094                     0                   352                   352  2026-11-30 23:55:05.466  2026-11-30 23:55:05.490  aeron:ipc                 aeron:ipc
            position  frame length  kind                  term offset      term id      session       stream              reserved  payload (hex)
                   0            43  DATA                            0    697683711   1411926094         1001                     0  6d65737361676520303a20
                  64            50  DATA                           64    697683711   1411926094         1001                     0  6d65737361676520313a207878787878 .. (18 bytes)

           recording  state            stream      session             start pos              stop pos                 bytes  started (UTC)            stopped (UTC)            source                    channel
                   1  INVALID            1002   1411926095                     0                  3104                  3104  2026-11-30 23:55:05.507  2026-11-30 23:55:05.538  aeron:ipc                 aeron:ipc
(recordingId=1) skipping data: INVALID

           recording  state            stream      session             start pos              stop pos                 bytes  started (UTC)            stopped (UTC)            source                    channel
                   2  VALID              1003   1411926096                     0                     0                     0  2026-11-30 23:55:05.568  2026-11-30 23:55:05.588  aeron:ipc                 aeron:ipc
(recordingId=2) Recording is empty

Java’s reader stops at an empty frame without a word. When that is before the recording’s stop position, dump says where the data ends and exits 2.

verify runs the checks ArchiveTool verify runs (positions aligned and in order, the last segment file’s frames, every segment file’s with -a) and prints its lines, but marks no entry and truncates no file. Where Java’s verify would change something, the line says so; exit status 1 when an entry would be marked INVALID:

(recordingId=0) OK
(recordingId=1) OK (INVALID in the catalogue: Java's verify would mark it VALID)
(recordingId=2) OK

A last fragment that straddles a page boundary with no data after it is not an error: Java asks whether to truncate the file and prints OK either way, so the line is OK with a note. A segment file that was skipped (a link, a FIFO, a name Aeron does not write) is named on standard error.

verify -checksum is not offered: it needs a Java checksum class.

Differences from ArchiveTool, on purpose

ArchiveToolergo-aeron archive-dir
Openingmaps the catalogue (describe ID read-write), the mark file and segment filesopens each file read-only with no-follow and non-blocking flags and reads by offset; a symbolic link, FIFO or directory named like an archive file is refused (segment files: skipped with a note)
A damaged filean exception, or a SIGBUS on a file that shrankone line naming the file and the length that does not fit, exit status 2; output up to it stands
errorsthe archive’s log, then the driver’s at the mark file’s aeronDirectorythe archive’s log only: that path is read from the file, so it is not followed
verifymarks entries INVALID or VALID, rewrites stop positions, asks to truncate a torn last fragmentchanges nothing and says what Java would change
Mark file linkfollows archive-mark.lnkfollows it too, and says so in the mark file row

The directory named on the command line may itself be a symbolic link (an operator’s own argument, as Kubernetes mounts often are); the files in it are read only where they are.

Disk use and time until full

archive-dir disk reads the directory twice, --between milliseconds apart (1000 by default), and prints one row for the volume (free bytes, size, bytes allocated to segment files, their growth per second, free bytes over that growth as the time until full), one per stream and one per recording. Bytes on disk are the blocks allocated: Aeron sets each segment file to its full length up front, and the file system allocates it as it is written. The Archive dir tab’s status line shows the same for the volume on each read. A preview of what a purge, truncate or detach would free comes with writer mode.

The offline source needs only the archive’s volume, and works on it mounted read-only: the tests run every archive-dir command on a copy whose files are mode 0444 in a directory of mode 0555, and check that no byte and no modification time changed.

In Kubernetes

See what a node’s media driver is publishing: ergo-aeron in a pod on that node, reading the driver’s directory through a read-only mount. It starts no Aeron client and adds no subscription (why). The files are in k8s/ergo-aeron.

The driver’s directory isUse
a hostPaththe DaemonSet and kubectl aeron
an emptyDir, and you can edit the driver poda sidecar
an emptyDir, pod left as it is, driver’s uid knownkubectl debug on the driver pod
an emptyDir, and you may run a root pod on the nodekubectl debug node/

Set up

# From a checkout. No JDK is needed: the image has no archive control reader.
docker build -f k8s/ergo-aeron/Dockerfile -t REGISTRY/ergo-aeron:TAG .
docker push REGISTRY/ergo-aeron:TAG          # or: kind load docker-image ...

kubectl create namespace ergo-aeron
kubectl -n ergo-aeron create configmap ergo-aeron-schemas --from-file=schemas/
# Set the image, hostPath, AERON_DIR and nodeSelector first.
kubectl apply -f k8s/ergo-aeron/daemonset.yaml

install -m 755 k8s/ergo-aeron/kubectl-aeron ~/.local/bin/   # any directory on PATH

Use

kubectl aeron nodes                      # the ergo-aeron pod of each node
kubectl aeron health                     # every node, or `health NODE`
kubectl aeron tui NODE                   # the terminal UI
kubectl aeron streams NODE               # or counters, errors, loss, driver, log
kubectl aeron messages NODE --stream 1001 --schema /schemas/trade.xml --follow

health exits 0 (OK or WARN), 1 (ALARM) or 2 (unreadable, timed out, or no running viewer pod); kubectl exec itself failing also exits 1. Anything after the node goes to ergo-aeron (subcommands). ERGO_AERON_NAMESPACE names another namespace.

From a terminal, Ctrl-C stops a --follow. With no terminal (a pipe, a script) Kubernetes leaves the process running in the pod after kubectl has gone, and it keeps cnc.dat and the stream’s log file open: after a driver restart that is /dev/shm space the node does not get back until it ends. The plugin ends such a run after ERGO_AERON_TIMEOUT seconds (default 600). A bare kubectl exec has no such bound; kubectl -n ergo-aeron delete pod POD clears what is left.

Schemas reach the pod either way:

Way--schema
the ergo-aeron-schemas ConfigMap (at most 1 MiB, optional)/schemas, or one file in it
kubectl cp trade.xml ergo-aeron/POD:/tmp/trade.xml (gone with the pod)/tmp/trade.xml

From another machine

From your machineNeeds
ssh -t SERVER 'kubectl aeron tui NODE'kubectl, the plugin and a kubeconfig on SERVER, all found by a non-interactive ssh command. -t gives the terminal UI its terminal
ssh -N -L PORT:127.0.0.1:PORT SERVER, then kubectl aeron ... as usualkubectl, the plugin and a copy of the kubeconfig on your machine

The second is for an API server that listens only on SERVER’s loopback, as kind’s does by default. PORT is the one in the kubeconfig’s server: https://127.0.0.1:PORT, and must be free on your machine; the kubeconfig is used unchanged:

ssh SERVER 'cat KUBECONFIG_FILE' > kind.kubeconfig   # the one kind wrote on SERVER
chmod 600 kind.kubeconfig       # it is the cluster's admin credential
grep server: kind.kubeconfig    # https://127.0.0.1:PORT
ssh -N -L PORT:127.0.0.1:PORT SERVER &
KUBECONFIG=kind.kubeconfig kubectl aeron tui NODE

What goes in the pod and on the node

SettingWhy
PodhostPath of the parent of the driver’s directory, readOnly: true; AERON_DIR names the driver’s directory under ita driver that deletes and recreates its directory (aeron.dir.delete.on.start) leaves a mount of the directory itself pointing at the deleted one
PodhostPath type: DirectoryDirectoryOrCreate would create it owned by root, which a non-root driver cannot write
PodCPU request without a matching limit: QoS Burstableit runs on the shared CPUs and takes no exclusive CPU
Podnon-root, drop: [ALL], read-only root filesystemreading needs nothing else
Driver podits aeron.dir inside a hostPath shared with this DaemonSetanother pod cannot see an emptyDir
Nodethe parent directory exists and the driver’s uid can write it
NodenodeSelector in the DaemonSet picks the driver nodeson a node without the directory the pod stays ContainerCreating

Never mount /dev/shm itself as the parent. Aeron’s default directory, /dev/shm/aeron-USER, sits directly under it, and mounting it would show the viewer every process’s shared memory on the node. Give drivers a directory of their own (aeron.dir=/dev/shm/aeron/driver). Whoever can kubectl exec into the viewer can read everything under the mounted parent.

The namespace must allow hostPath volumes: the Pod Security baseline and restricted levels refuse them.

File permissions

Aeron’s C driver creates its files through its umask. The viewer must be able to read them:

Driver umaskFiles others can readThe viewer needs
022yesnothing: any uid
027its groupsupplementalGroups: [DRIVER_GID]
077norunAsUser: DRIVER_UID

A viewer that cannot read them is not told Permission denied: it says cannot read the Aeron driver ... Timed out waiting for CnC file, the same as for a directory with no driver. Compare ls -ln of the driver’s directory (kubectl exec into the driver pod) with the viewer’s id. Running as the driver’s own uid makes the files writable by ownership, and the read-only mount still refuses every write (Read-only file system).

A read-only mount is also why the one write action, driver terminate, does not work here.

Sidecar sharing an emptyDir

A second container in the driver pod, with the driver’s volume mounted read-only. No hostPath and no capability. In the pod spec:

containers:
  - name: driver   # as before, plus:
    volumeMounts: [{name: aeron, mountPath: /aeron}]    # aeron.dir=/aeron/driver
  - name: ergo-aeron
    image: REGISTRY/ergo-aeron:TAG
    env: [{name: AERON_DIR, value: /aeron/driver}]
    resources: {limits: {cpu: 100m, memory: 128Mi}}
    securityContext:
      runAsUser: 65534    # or the driver's uid: see File permissions
      runAsGroup: 65534
      runAsNonRoot: true
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities: {drop: [ALL]}
    volumeMounts:
      - {name: aeron, mountPath: /aeron, readOnly: true}
      - {name: tmp, mountPath: /tmp}    # for `kubectl cp` of schemas
volumes:
  - {name: aeron, emptyDir: {medium: Memory, sizeLimit: 256Mi}}
  - {name: tmp, emptyDir: {sizeLimit: 16Mi}}
kubectl exec -it DRIVER_POD -c ergo-aeron -- env TERM="$TERM" ergo-aeron --no-history
  • A Guaranteed pod stays Guaranteed only if every container’s requests equal its limits; the limits-only block above does that. A fractional CPU leaves the container in the shared CPU pool.
  • Not for a pod labelled ergon.io/latency: hot: the latency pod policy wants whole CPUs, among other things, from every container. Give that driver a hostPath and use the DaemonSet.
  • kubectl aeron does not find it: it looks only for the DaemonSet’s pods.

kubectl debug on the driver pod

An ephemeral container beside the running driver, which is not restarted. It shares the driver container’s processes, so the driver’s own filesystem, emptyDir mounts included, is at /proc/1/root/ (pid 1 being the driver container’s first process).

echo '{"securityContext":{"runAsUser":DRIVER_UID,"runAsGroup":DRIVER_GID}}' > user.json
kubectl debug DRIVER_POD --target=DRIVER_CONTAINER --image=REGISTRY/ergo-aeron:TAG \
    --profile=restricted --custom=user.json -c ergo-aeron -- sleep 3600
kubectl exec -it DRIVER_POD -c ergo-aeron -- env TERM="$TERM" ergo-aeron \
    --no-history --aeron-dir /proc/1/root/PATH/TO/AERON_DIR

What it takes to read /proc/1/root, for a driver container that adds no capabilities:

Debug container runs asDriver not rootDriver root
the driver’s uid and gid, no capabilityworks—
root with SYS_PTRACE (kubectl’s default profile, if nothing sets a uid)worksnot needed
root without SYS_PTRACE (--profile=netadmin)refusedworks
another non-root uidrefused—
  • For a root driver, leave out --profile and --custom.
  • A pod-level runAsUser applies to the debug container too.
  • Namespaces enforcing Pod Security baseline or restricted refuse SYS_PTRACE, which the default profile adds even with --custom; the command above passes both levels.
  • Refused reads show as cannot read the Aeron driver, not Permission denied.
  • The mount here is not read-only: as the driver’s uid or root, the container can write the driver’s files.

kubectl debug node/

For a driver whose directory is an emptyDir, or a node without the DaemonSet:

uid=$(kubectl get pod DRIVER_POD -o jsonpath='{.metadata.uid}')
node=$(kubectl get pod DRIVER_POD -o jsonpath='{.spec.nodeName}')
kubectl debug node/$node --image=REGISTRY/ergo-aeron:TAG --profile=general -- sleep 3600
# It prints the debug pod's name, node-debugger-NODE-xxxxx.
# No subcommand opens the terminal UI; or add streams, health, ...
kubectl exec -it node-debugger-NODE-xxxxx -- env TERM="$TERM" ergo-aeron \
    --aeron-dir "/host/var/lib/kubelet/pods/$uid/volumes/kubernetes.io~empty-dir/VOLUME"
kubectl delete pod node-debugger-NODE-xxxxx

VOLUME is the emptyDir’s name in the driver pod, followed by the driver directory’s path inside it, if any. Copy schemas in with kubectl cp.

  • The node’s filesystem is mounted at /host writable, and the pod runs as root: nothing but the tool’s own read-only behaviour protects the driver. Run nothing else there, and delete the pod when done.
  • The pod sees the mounts that existed when it started. A memory-backed emptyDir made later (a restarted driver pod) needs a new debug pod.

Check it

k8s/ergo-aeron/e2e.sh builds the image and, on a throwaway kind cluster, checks the health exit codes, reading and decoding, the three umasks, a driver restart, the time limit and Ctrl-C, refused writes and kubectl debug node/. It needs Linux with docker (and buildx), kind, kubectl and script, and has run on x86-64 with kind 0.33.0. The sidecar, driver-pod kubectl debug and other-machine sections are not part of it; they were run by hand on the same kind version with Kubernetes 1.37.

One core, two front ends

ergo-aeron-tools is a library with the behaviour in it, and two thin front ends over it behind features: the command line (cli) and the terminal (tui, which needs cli). A desktop front end can be added the same way, with no behaviour of its own.

cnc.dat, mapped read-only→read: checks the file's lengths before each read that trusts them, then returns a plain-data Snapshot, with each counter's key, registration id and owner id→Monitor: poll / update, apply(Action)→screen(): rows, matches, selection, health
a stream's log file, read with no subscription→Tap::poll: whole messages, skips counted (a Feed thread polls it each millisecond)→Monitor::take: decoded with the schemas, per-type counts
embedded mode: a channel URI, joined through the tool's own Embedded driver→Viewer::poll: a guarded subscription that leaves when behind and rejoins live, and counts what its driver filled in for lost data from the loss report (on a Feed thread too)→Monitor::take
a decoded message's fields, and those of messages nested in its var data, with what the schema says about them (its semanticType, the name of its type, its description, its extension attributes), read by ergo-sbe-inspect→Interpreter: the rules that say what a value means, first match wins: a converter you registered, a decimal the schema declares, the rest of the schema, the field's name, the value→Messages: the meaning beside the raw value, in the decoded column, the preview and the message's JSON
the log file of the stream whose Streams detail is open (metadata only, a few hundred bytes)→Log::open: opened by Monitor itself while the detail is open (when it opens, moves to another stream or a new read arrives), not fed in by a front end→screen().detail: the log's main fields above the row's columns
an archive directory's files, opened read-only; an archive's control session, read requests only→ArchiveFeed: a thread per source, dir_tab each read period; for Recordings a Listing over Online that lists in full once a minute and asks only for new and not-yet-stopped recordings between→Monitor::take_archive: the Recordings and Archive dir tabs, recording lag from the counters; with no --control, an archive seen in the counters (archive::seen) adds a counters-only Recordings tab, and the session is asked for only by its key
one recording, replayed by the archive back to the tool (a read: start_replay, no stop request)→Replay::poll: whole messages from the replay's own session (on a Feed thread that waits for room instead of dropping)→Monitor::take_replay: the Payload tab, decoded and searched as the Messages tab
Counters detail or counters --explain→counter_docs looks up system and type ids; links reads ids and relationships from the full snapshot→explain: detail rows and jump targets for the terminal, text or JSON fields for the command line
core (no features): tabs, tables and JSON, the rules that say what the Messages tab's values mean (a new Monitor starts with the standard ones; none: the values stay as they are), health, key table, regular-expression filter and preview search, view state with the history picker, log inspector, action table and write gate with the action log (a write takes the approval only once its intent line is on disk), the writer flow (menu, preview, typed token, result), a heartbeat-only read for waiting on a driver, embedded driver and viewer, history file, archive directory reader, recording lag, and (feature archive, on by default) the read-only archive session through the tool's own driver with --embedded else the attached one; no terminal or window type
presentation (style, with cli): shared colour roles, icon sets and row styling for both front ends, and the roles of a decoded message's text
terminal (tui): keys → Key, clicks → Action; opens the tap, viewer, replay or schemas the core asks for; starts the archive readers (the control one also when the core asks for it); runs a confirmed write off the draw thread; turns mouse capture on and off and writes a copied preview as OSC 52; draws screen() with colour and status iconscommand line (cli): flags → reads, tap or viewer polls (with interpret::toml for --converters), a log walk, archive reads, a gated action or the history; prints the core's tables with optional styling, JSON, counter explanations or messages
LayerHoldsNever holds
Core (no features)reading the driver (read, Snapshot); the passive tap (tap::Tap) and its reader thread (tap::Feed); embedded mode’s own driver and guarded viewer (embedded); the history file (history); decoding messages (messages) and what their values mean (interpret); the log inspector (log), which Monitor itself calls to read the open Streams detail’s log metadata; the action table, its write gate and the one run of a write (actions), the action log whose intent line the write requires (action_log), the terminal UI’s writer flow of menu, preview, typed token and result (writer), and a heartbeat-only read (snapshot::pulse) for waiting on a driver; the archive readers: an archive directory’s files (archive_dir) and a read-only control session (feature archive, on by default; it alone needs a JDK to build), a recording’s replay back to the tool (archive::replay) plus recording lag and the archive seen in the counters (archive), with the archive tabs’ reader threads (archive::ArchiveFeed); the counter catalogue (counter_docs), what a counter links to (links) and both as text and JSON (explain); every tab as a table and as JSON; health and the version guard; the key table; the list filter and the preview’s regex search; the view state of every tab (selection, sort, filter and its matches, detail, preview with its matches, pause, mark, help), changed only by Monitor::applyany terminal, window or command-line type
Presentation (style, with cli)the colour role of each meaning, the four icon sets and their detection, and what a row of each tab looks like (healthy, lagging, dead), read from the table’s cells: one definition for both front ends (Colour and icons)behaviour of the view: it never changes the core’s rows, text or JSON
Command lineturning flags into reads (one, two for health, or one per --watch period), tap polls (messages), a log walk (log), archive reads (recordings, recording, recording-lag, archive-dir) or a gated action (driver terminate, which the core runs and waits on), and printing the core’s tables with optional colour and icons, JSON, counter explanations or messagesformatting of its own
Terminalturning keys and mouse events into the core’s Key and Action, opening the tap, viewer, replay or schemas the core asks for (the Streams and Recordings tabs, the history picker), starting the archive readers (the control one also when Monitor::take_connect_request asks for it) and handing their rows to Monitor::take_archive, running a confirmed write off the draw thread (writer::InFlight), and drawing Monitor::screen()selection, filter, search, sort or health logic

The command line takes its reads from a function (cli::run_with), so the command outputs in this book are what the real command prints for a hand-built driver read, and a test fails when they drift.

The core never owns the event loop. A front end calls Monitor::poll on its own tick and Monitor::apply (or Monitor::key) for input, then draws Monitor::screen(). So behaviour is tested once, on the core alone, with scripted actions and no terminal; the terminal’s tests cover drawing, mouse hit-testing and key mapping only.

just policy keeps it that way: it runs cargo tree -p ergo-aeron-tools --no-default-features and fails if a terminal, command-line or window crate appears.

Cluster client

ergo-aeron-cluster is an experimental Rust client for Aeron Cluster. It uses rusteron for transport and ergo-sbe-generated codecs for Aeron’s Cluster protocol.

Hobby project. Do not use it as a production substitute for official Aeron Cluster client support.

Scope

The crate implements client-side operations:

  • synchronous and poll-driven connection;
  • ingress offer and explicit try_claim;
  • egress polling into one listener: AeronCluster::poll, or controlled_poll_egress for per-fragment flow control;
  • authentication challenges and credentials;
  • keep-alives and close requests;
  • session events, administrative responses, and leader changes.

The Java Aeron process still provides the media driver, archive, consensus module, clustered services, election, recovery, and operational tooling. This crate implements none of those server-side components.

Where the crate sits between your loop and the Java cluster:

your loop, one thread
poll, keep_alive_if_due, offer
AeronCluster
offer / try_claim: ingress
poll(listener): egress
keep_alive_if_due: every message_timeout / 4,
clamped to 50–1000 ms
a 32-byte session header a message
ergo-sbe codecs
generated at build from
cluster/schemas/*.xml
rusteron-client
exclusive publication: ingress
subscription: egress
media driver at aeron_dir: Aeron's, not this crate's
The Java Aeron process provides
the media driver, archive, consensus module, clustered services, election, recovery and
operational tooling. ergo-aeron-cluster implements none of those server-side components.
member · leader
consensus module, clustered
services, archive, media driver
member · follower
member · follower
connect(): blocks
without ingress_endpoints: connect_single, one ingress channel,
blocking adds (5 s each), then the handshake until SessionEvent(OK)
with ingress_endpoints: connect_fanout, async adds to every member,
the adds and the handshake under one message_timeout deadline
connect_async(), then poll()
CreateTransport → SendConnect → PollResponse → Done:
egress and ingress added by async adds, each step
one unit of work
Failover never blocks poll
a NewLeaderEvent starts an async add to the new
leader; offers fail NotConnected until it
connects, within message_timeout
Aeron Cluster: what ergo-aeron-cluster does, and what stays in Java
ergon book · Cluster client › Scope
Client side only. The session's states: Session lifecycle, below.
Your process: Rust
Java Aeron Cluster: none of it in this crate
ingress
egress

Session lifecycle

Text alternative. The client has one ingress publication to the leader and one egress subscription. Until the handshake succeeds it is Closed.

  1. Connect. connect() offers one SessionConnectRequest, which lands once, because each request opens a session. If the cluster sends a Challenge, the client answers with a ChallengeResponse under a new correlation id. A SessionEvent(OK) that echoes the current id gives Connected. message_timeout bounds the handshake.
  2. Keep alive. poll never sends keep-alives. Call keep_alive_if_due from the same loop. While Connected, it sends a 24-byte SessionKeepAlive every message_timeout / 4, clamped to 50–1000 ms.
  3. Leader lost. When the bound egress image closes, or an offer is refused with NotConnected or Closed, the state becomes AwaitingNewLeader. new_leader_timeout bounds the wait.
  4. New leader. A NewLeaderEvent on egress carries the new term, the leader member id and every member’s ingress endpoint. The client picks the leader’s entry, adds an ingress publication there and restarts the clock, now bounded by message_timeout. Once the publication connects, the client adopts the new term and leader, and the state returns to Connected.
  5. Close. SessionEvent(CLOSED) gives PendingClose, and the same poll then moves it to Closed. An offer refused with MaxPositionExceeded gives PendingClose until the next poll. close() sends a SessionCloseRequest while Connected and goes straight to Closed.

Each message carries a 32-byte session header. Failover and close never block poll, but offers fail with NotConnected from leader loss until the new publication connects. The session closes if no NewLeaderEvent comes within new_leader_timeout, or its publication does not connect within message_timeout. This book records no failover timings. Endpoints and field values in the animation are illustrative.

Features and harness

The published crate has one feature, static, on by default. It turns on rusteron’s static feature, which links Aeron’s C into your binary, so the binary runs with no libaeron library on the loader path. To link Aeron dynamically instead, depend on the crate with default-features = false; then libaeron must be on the loader path (cargo run and cargo test put it there):

ergo-aeron-cluster = { version = "0.1", default-features = false }

rusteron builds Aeron’s C from source either way, so the build needs CMake and a C compiler. On Linux, static also links libuuid (Debian and Ubuntu: uuid-dev) and libatomic (shipped with gcc); libbsd (libbsd-dev) is needed with or without it.

Java Cluster launch support lives in the unpublished workspace crate ergo-aeron-cluster-test-harness and requires a JDK (17 or newer; CI runs Temurin 25) plus the Aeron release jars, which its build script downloads. See Java for Archive and Cluster for which Java to run the cluster on and the recommended JVM and Aeron settings:

just fetch-aeron-jars
just test-aeron-cluster-harness

The harness, examples, integration tests, reference codecs, and benchmarks are excluded from the published crate package.

Verify the crate

cargo test -p ergo-aeron-cluster
cargo clippy -p ergo-aeron-cluster --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc -p ergo-aeron-cluster --no-deps
cargo bench -p ergo-aeron-cluster --no-run
cargo package -p ergo-aeron-cluster --list --allow-dirty

Run just bench-cluster for the maintained codec comparisons. See sbe/BENCHMARKS.md for the common benchmark rules.

Limitations

Limitations, Aeron and rusteron versions, schema identities, failure modes and what CI runs against a live cluster: Compatibility.

Apache-2.0.

Cluster tutorial

End-to-end walkthrough: launch a test cluster, connect a session, offer messages, poll events, send keep-alives, and close. The best starting point for the ergo-aeron-cluster client lifecycle.

Source: samples/cluster-tutorial/src/main.rs

See also: Cluster client overview

just fetch-aeron-jars
cargo run --manifest-path samples/cluster-tutorial/Cargo.toml

Requires a JDK 25 (17 or newer) and the Aeron release jars; see Java for Archive and Cluster.

SessionBuilder

SessionBuilder is the supported configuration entry point:

use std::sync::Arc;
use std::time::Duration;
use ergo_aeron_cluster::{SessionBuilder, StaticCredentials};

fn main() -> Result<(), ergo_aeron_cluster::ClusterError> {
    let session = SessionBuilder::default()
        .ingress_channel("aeron:udp?endpoint=localhost:9010")?
        .egress_channel("aeron:udp?endpoint=localhost:9020")?
        .credentials(Arc::new(StaticCredentials::from_utf8("user:pass")))
        .message_timeout(Duration::from_secs(5))?;

    session.validate()?;
    let mut client = session.connect("/path/to/aeron-dir")?;
    client.offer(b"application payload")?;
    client.close()
}

Connection remains poll-driven internally; the crate does not require Tokio or another async runtime. AsyncClusterConnect is a poll-driven Aeron state machine, not a Rust Future. When the application owns the poll loop, the shortest supported path calls SessionBuilder, connect_async, default_idle, poll_connect_until_done and finish in that order:

#![allow(unused)]
fn main() {
use ergo_aeron_cluster::{default_idle, poll_connect_until_done, SessionBuilder};

fn connect(aeron_dir: &str) -> Result<ergo_aeron_cluster::AeronCluster, ergo_aeron_cluster::ClusterError> {
    let builder = SessionBuilder::default()
        .ingress_channel("aeron:udp?endpoint=localhost:9010")?
        .egress_channel("aeron:udp?endpoint=localhost:9020")?;
    let mut connecting = builder.connect_async(aeron_dir);
    let mut idle = default_idle();
    poll_connect_until_done(&mut connecting, &mut idle)?;
    connecting.finish()
}
}

Drive poll / step yourself when you need to inspect connect steps or plug in a custom idle strategy.

No poll waits on the media driver. AsyncClusterConnect::poll adds the egress subscription and ingress publication, and the publication a REDIRECT asks for, with Aeron’s async add and picks them up on later polls. poll handles a NewLeaderEvent the same way: the session stays AwaitingNewLeader until the new leader’s publication has connected, for up to the message timeout. Only the first poll, which creates the Aeron client, can wait, and only while the media driver is not running yet.

Check message sizes once, at start-up: offer takes payloads up to ingress_max_message_length() and try_claim up to ingress_max_payload_length() (when smaller), each less AeronCluster::SESSION_HEADER_LENGTH. A REDIRECT or a new leader re-adds the configured ingress channel, changing only a unicast endpoint (IPC and multicast channels stay as they are), so the limits hold across failover.

Multi-member ingress: ingress_endpoints

For first-connect against a cluster whose current leader isn’t known ahead of time, use ingress_endpoints instead of (or alongside) ingress_channel:

let session = SessionBuilder::default()
    .ingress_endpoints("0=host-a:9010,1=host-b:9010,2=host-c:9010")?
    .egress_channel("aeron:udp?endpoint=localhost:9020")?;

The grammar is member_id=host:port pairs separated by commas, with no aeron: prefix, member IDs need not be sorted or contiguous. The setter parses and validates eagerly: a missing =, non-numeric member ID, empty endpoint, empty map, or duplicate member ID fails immediately at the call site rather than at validate() or the first poll().

The fan-out sends one SessionConnectRequest, not one per member, as Java’s client does: a second copy reaching the leader would leave a session behind.

The fan-out skips a member whose publication cannot be added and connects through the others. The add’s error ends the connect only once no member is left. A REDIRECT keeps only the leader’s member, so a leader that cannot be added still ends the connect. Java’s client skips such a member too, but adds it again after a “temporarily unavailable” error; this client does not. A connect that times out names the skipped members in ClusterError::ConnectFailed, on connect_async too, in place of its ClusterError::Timeout.

Animation, in words: with three endpoints, connect (and connect_async) starts an async add of one ingress publication per member. It takes the first publication that connects (here member 0, a follower; illustrative) and sends one SessionConnectRequest with a fresh correlation id (7) on it alone. The follower answers SessionEvent(REDIRECT) echoing 7 and naming leader member 2. The client drops member 0’s publication, closes member 1’s, and keeps member 2’s, which has been connecting since the start, so no new add is needed (when the redirect names the same endpoint string as the map). It sends a new request with id 8 once that publication connects; only a SessionEvent or Challenge echoing the current id counts. The leader answers SessionEvent(OK) echoing 8, and the client keeps only the leader’s publication: one session, two round trips (one if the first member to connect leads). When the leader is already known, a single ingress_channel is cheaper: the other publications exist only to be closed.

Egress listeners

Implement EgressListener (only on_message is required) and call AeronCluster::poll every loop iteration. One call reads egress, passes this session’s messages to the listener (other sessions’ are dropped), and drives the session state: failover to a new leader, the leader and message timeouts, close. A fragment_limit of 0 drives the state alone.

#![allow(unused)]
fn main() {
use ergo_aeron_cluster::{AeronCluster, ClusterError, EgressListener};

struct Fills(usize);

impl EgressListener for Fills {
    fn on_message(&mut self, _session: i64, _timestamp: i64, payload: &[u8]) {
        self.0 += payload.len();
    }
}

fn run(client: &mut AeronCluster) -> Result<(), ClusterError> {
    let mut fills = Fills(0);
    loop {
        client.poll(&mut fills, 10)?;
        client.keep_alive_if_due()?;
    }
}
}
CallbackDefaultOverride to
on_messagerequiredhandle application payloads
on_message_with_reserved_valuecalls on_messageread the Aeron header’s reserved value (a send stamp)
on_session_event, on_new_leaderignoreobserve lifecycle; the client acts on them itself
on_challenge, on_admin_responseignoreobserve auth challenges, snapshot replies
on_extension_messageignoreread frames of another template or schema

For per-fragment flow control, implement ControlledEgressListener and call AeronCluster::controlled_poll_egress: on_message and on_extension_message return a ControlledAction (Abort, Break, Commit, or Continue) matching Aeron’s ControlledFragmentHandler.Action.

A payload slice is valid only inside the callback: copy what you keep.

Protocol errors, listener panics, keep-alive failures, publication failures, and reconnect failures are returned as ClusterError. Application payloads, credentials, challenges, and binary response data remain byte slices. Text fields declared by the protocol are validated before being exposed as &str.

The high-level client, configuration, listener, state, error, offer, and claim types are the consumer-facing surface. The generated protocol codecs are also reachable, for advanced direct encode/decode, through the cluster_codec_types module, but that module is #[doc(hidden)] and not a stable API: it exists for repository tests and low-level experimentation, and its shape may change in any release. Normal applications should use AeronCluster.

Multi-message framing

Ergon supports two framing approaches for adjacent messages, and an AnyMessage dispatch enum for multi-message streams where the next type isn’t known until runtime.

Normal Cluster applications use AeronCluster and its egress listeners. The protocol-codec examples below illustrate framing through the repository’s cluster_codec_types test/benchmark seam, which is not a stable consumer API.

Animation, in words: the feature tour buffer holds a Heartbeat (bytes 0 to 24) then a Note (24 to 56). AnyMessage::try_decode at offset 0 reads the 8-byte header, checks schemaId 77 and matches templateId 1. Heartbeat has no tail, so 8 + blockLength 16 moves the offset to 24. The header at 24 names the Note. Its get_metadata().remaining() starts at 36, which is the Note’s own length prefix, not the next message. The staged into_body_as_str() reads the length and the 16-byte body, and the complete stage gives 24 + 8 = 32 bytes, so the offset reaches 56 and the loop ends. No byte is read twice. An unknown templateId (an illustrative third frame) makes try_decode return UnknownTemplateLength. blockLength covers only the fixed block, so the chain stops. FrameCursor with a 4-byte length prefix per frame skips that frame as Unknown. For a fixed-only SessionMessageHeader, remaining() at byte 32 is exactly the following SessionKeepAlive. These are counts from the generated code, not timings.

Two framing approaches

1. Back-to-back with encoded length

Pre-compute each message’s exact size, lay them out at known offsets, and validate after encoding. Safest when you know all messages ahead of time.

// Size every message from its own payload length.
let len_a = MsgAEncoder::compute_length_with_header(data_a.len());
let len_b = MsgBEncoder::compute_length_with_header(data_b.len());

let mut buf = vec![0u8; len_a + len_b];

// Encode MsgA at offset 0.
let a_len = MsgAEncoder::wrap_and_apply_header(&mut buf[..len_a], 0)
    .fixed(&fields_a)
    .data(data_a)?
    .encoded_length_with_header();
assert_eq!(a_len, len_a);

// Encode MsgB at offset len_a.
let b_len = MsgBEncoder::wrap_and_apply_header(&mut buf[len_a..], 0)
    .fixed(&fields_b)
    .data(data_b)?
    .encoded_length_with_header();
assert_eq!(b_len, len_b);

// Both schemas are known, so their tails determine their message boundaries.
let wire = &buf[..len_a + len_b];

2. Stream / remaining() slot

Write sequentially; use remaining() to find where the next message starts. Idiomatic for Aeron cluster sessions where a SessionMessageHeader is immediately followed by application payload.

use ergo_aeron_cluster::cluster_codec_types::*;

let mut buf = [0u8; SessionMessageHeaderEncoder::compute_length_with_header()
    + SessionKeepAliveEncoder::compute_length_with_header()];

// Encode the outer message. `fixed()` writes the required body so a reused
// buffer cannot publish leftover bytes.
let tail = SessionMessageHeaderEncoder::wrap_and_apply_header(&mut buf, 0)
    .fixed(&SessionMessageHeaderFixedFields {
        leadership_term_id: 7,
        cluster_session_id: 99,
        timestamp: 42,
    })
    .into_remaining_mut();

// into_remaining_mut() returns the unwritten tail.
let keep_alive_len = SessionKeepAliveEncoder::wrap_and_apply_header(tail, 0)
    .fixed(&SessionKeepAliveFixedFields {
        leadership_term_id: 7,
        cluster_session_id: 99,
    })
    .encoded_length_with_header();
assert_eq!(keep_alive_len, SessionKeepAliveEncoder::compute_length_with_header());

// Decode: remaining() gives bytes after the first message.
let smh = SessionMessageHeaderDecoder::decode(&buf, 0)?;
let tail = smh.get_metadata().remaining();
assert_eq!(tail.len(), SessionKeepAliveEncoder::ENCODED_LENGTH);

AnyMessage dispatch

Cluster sessions multiplex many message types on a single stream. AnyMessage::try_decode reads the 8-byte session SBE header, validates its schema identity, and selects the template. For known templates it also checks the acting fixed-body extent. Dynamic tails are checked when consumed:

use ergo_aeron_cluster::cluster_codec_types::*;

fn dispatch(data: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    match AnyMessage::try_decode(data, 0)? {
        AnyMessage::SessionMessageHeader(decoder) => {
            // This wraps application payload. The application owns its
            // schema; do not recursively dispatch it as Cluster protocol.
            let payload = decoder.get_metadata().remaining();
            println!("application payload: {} bytes", payload.len());
        }
        AnyMessage::SessionEvent(decoder) => {
            let code = decoder.code();
            let (detail, _) = decoder.into_detail_as_str()?;
            println!("event {code}: {detail}");
        }
        AnyMessage::NewLeaderEvent(decoder) => {
            let (endpoints, _) = decoder.into_ingress_endpoints_as_str()?;
            println!("new leader at {endpoints}");
        }
        AnyMessage::Challenge(decoder) => {
            let (chal, _) = decoder.into_encoded_challenge()?;
            println!("challenge: {} bytes", chal.len());
            // respond to challenge...
        }
        AnyMessage::AdminResponse(decoder) => {
            let (msg, after) = decoder.into_message()?;
            let (payload, _) = after.into_payload()?;
            println!("admin response: {msg:?}, {} payload bytes", payload.len());
        }
        AnyMessage::SessionKeepAlive(_) => {
            // heartbeat: nothing to do
        }
        AnyMessage::Unknown { .. } => {
            // Produced by decode_frame when an external length is supplied.
        }
        _ => {
            // Other known session templates are not handled by this example.
        }
    }
    Ok(())
}

SBE headers do not carry a complete message length. try_decode returns UnknownTemplateLength for an unknown template because its tail cannot be located without the schema. Use AnyMessage::decode_frame / FrameCursor with an external frame length when unknown templates must be preserved or skipped. FrameCursor, and the DecodedFrame that decode_frame returns, are items of a generated codec module; cluster_codec_types does not re-export them. The high-level Cluster client can ignore an unknown protocol message because Aeron already supplies the fragment boundary.

Metadata

Every message decoder exposes get_metadata(), which returns its <Message>DecoderMetadata view (CarDecoderMetadata for Car):

MethodReturns
buffer()The entire original &[u8] buffer
remaining()Bytes after the acting fixed block (&buffer[limit()..])
message_offset()Absolute offset of this message’s frame start within buffer()
limit()End of the acting fixed block (not the full frame when tails follow)

Metadata remaining() starts immediately after the fixed block. That is the application payload for a fixed-only SessionMessageHeader; for a message with groups or var-data, it starts at that message’s first tail. To locate the next message after a tailed message, complete its staged walk and use the complete stage’s remaining(). Calling the base decoder’s full-length helper instead requires a separate tail scan.

Cluster compatibility

Supported stacks

ComponentVersionNotes
Aeron Java/C media driver1.54.3Maven Central release jars pinned in .upstream-pins; archive + consensus module
Aeron Cluster Java1.54.3clustered service container
rusteron (Rust bindings)0.3.6 (workspace Cargo.toml)rusteron-client, rusteron-media-driver; bundles Aeron C 1.54.3 (the tutorial sample also uses rusteron-archive). ergo-aeron-cluster turns rusteron’s static feature on by default, so a binary links Aeron’s C statically and runs without a libaeron beside it; default-features = false links it dynamically instead. rusteron builds Aeron’s C from source with CMake and a C compiler either way. static also links libuuid and libatomic on Linux (libbsd is linked on Linux with or without it). rusteron-archive also needs Java and Gradle at build time to build the Aeron archive jars, when they are not already built (Java)
ergo-sbe (codec generator)0.1.xschema 111 session + mark codecs
Rust1.99+the workspace rust-version (the cluster Cargo.toml declares none); edition 2024. CI builds the cluster crate with 1.99.0; the MSRV job checks ergo-sbe only
OSLinux x86-64 and arm64CI runs the cluster unit tests on ubuntu-24.04 and ubuntu-24.04-arm, and the live-cluster harness on ubuntu-24.04 only. macOS is not run in CI
Java25 (17+)Archive and Cluster; the test harness runs Temurin 25 in CI (21 for the Aeron 1.46.8 compatibility job). Java for Archive and Cluster

Schema identities

SchemaIdSBE versionsemanticVersion
Aeron Cluster Session111185.4
Aeron Cluster Mark11025.4

These are pinned in cluster/schemas/ and generated by cluster/build.rs. The generated codec API is unstable: use the high-level AeronCluster client, not the cluster_codec_types module directly.

Failure modes

The client handles these documented transitions:

TriggerExpected behaviour
Leader loss (the session’s egress image closes / publication CLOSED)Session moves to AwaitingNewLeader and polls for NewLeaderEvent
NewLeaderEvent (the last one in a poll)Bind to the image that delivered it; add the leader’s ingress publication without waiting; Connected once it connects, Disconnected if it has not within the message timeout
SessionEvent(CLOSED)Session moves to PendingClose, then Closed, even while a new leader’s publication is pending
Redirect during connectFollow leader_endpoints to the new leader
A member’s publication cannot be added (ingress_endpoints)Skip the member; Java does too, but adds again after a “temporarily unavailable” error. The add’s error once no member is left, or when a REDIRECT names a leader that cannot be added; a connect that times out names the skipped members
Handshake event larger than one MTUReassembled before it is parsed, as Java’s EgressPoller does
New ingress publication (redirect or new leader)Keep every unicast ingress channel setting but the endpoint, and re-add IPC and multicast channels unchanged, so the message limits do not change
Auth challengePass to CredentialsSupplier, send ChallengeResponse
Auth rejectionClusterError::AuthRejected with the cluster’s detail, at once
SessionEvent(ERROR) answering the connect (session limit, client version)ClusterError::ConnectFailed with the cluster’s detail, at once
Connect requestSent once; a challenge response or a redirect sends a new one
close()SessionCloseRequest while connected (up to three offers under back pressure), then Closed
Snapshot admin requestUp to three claims under back pressure, then a retryable ClusterError::Publication
Ingress publication at its maximum positionThe offer returns MaxPositionExceeded; the next poll leaves the session Closed
Egress frame of another SBE schemaEgressListener::on_extension_message; skipped during connect
Timeout (connect / poll / new-leader)ClusterError::Timeout / ClusterError::Disconnected
Listener panicClusterError::ListenerPanicked, session continues
Malformed egress frameClusterError::ProtocolError
Payload too largeClusterError::PayloadTooLarge
Publication backpressureRetryable ClusterError::Publication
connect()
Connected
ingress to the leader, session active
AwaitingNewLeader
waiting for a leader
PendingClose
poll() moves it to Closed
Closed
terminal
Err, no state yet
AuthRejected, ConnectFailed, Timeout, or an Aeron, channel or builder error
close() from any state but Closed
sends SessionCloseRequest only when Connected with ingress connected, offering it up to 3 times under back pressure
close() again
Err(SessionClosed)
Blue: the leader-change path. Orange: the close and error exits. Each arrow names its trigger; every exit to Closed is shown.
SessionEvent(OK)
fails
leader lost: egress image down on poll,
or an ingress offer NotConnected / Closed;
or a NewLeaderEvent
new leader’s ingress connected:
adopt its term and leader
NewLeaderEvent: re-add ingress, rebind egress, restart the clock;
or the new egress closed first: drop the add, wait again
SessionEvent(CLOSED),
or ingress MaxPositionExceeded
SessionEvent(CLOSED): drops the pending publication
timeout → Err(Disconnected)
No new leader’s ingress pending: new_leader_timeout, the configured value, else 2 × the leader heartbeat from the OK, or 20 s when the OK has none.
A new leader’s ingress pending: message_timeout.
the same poll() after CLOSED,
the next one after MaxPositionExceeded
Aeron Cluster client: session states, triggers and exits

What CI runs against a live cluster

The harness (cluster-test-harness/tests/) runs in ci.yml (aeron-cluster-integration, Aeron 1.54.3, Java 25) and in cluster-compatibility.yml (Aeron 1.46.8, Java 21, when the cluster crate, the harness, sbe/src/, a manifest, Cargo.lock, the toolchain pin, the Aeron jar pins or fetch script, or the recipes it runs change; scripts/check-workflow-paths.sh fails if its filter drops one).

CoveredTest file
3-node connect, leader failover, redirectfailover.rs, failover_own_driver.rs, client_parity.rs, nonblocking.rs
New leader that never connects times outnonblocking.rs (a_new_leader_that_never_connects_times_out)
SessionEvent(CLOSED) while a new leader is pendingnonblocking.rs
Ingress channel settings kept across failover and redirectingress_channel_settings.rs
Fragmented egress reassembled by pollegress_fragmentation.rs
poll with fragment_limit 0 reads nothing but finishes a failovernonblocking.rs
Restart, reconnect, quorum loss, log recoveryrestart.rs
Null, simple and empty credentials; a challenge answered correctly; wrong credentials and a wrong challenge answer rejected with ClusterError::AuthRejectedauth.rs
Cluster closes a session that sends no keep-alives; keep-alives hold one openclient_parity.rs
One connect request per connect; a connect error fails the connect at once; session limitclient_parity.rs
A fan-out connect past a member that cannot be added; every member failing; the timeout naming the skipped memberclient_parity.rs
A handshake event spanning several fragments, on the async, blocking and fan-out connectsclient_parity.rs
Dropping an async connect releases its subscription and publications on a shared Aeron clientclient_parity.rs
Reaching the ingress maximum position closes the sessionclient_parity.rs
controlled_poll_egress (Abort, Break, Commit, Continue, lifecycle events, listener panic recovery)client_parity.rs
Admin snapshot request answered on on_admin_response: OK when authorised, UNAUTHORISEDACCESS by default, ERROR for an unknown request typeadmin_snapshot.rs

The harness lets the async connect timeout expire only after a member was skipped, which returns ClusterError::ConnectFailed (client_parity.rs). Unit tests in cluster/src/ (run by ci.yml’s test job) cover challenge dispatch (egress.rs), the challenge response (credentials.rs, client.rs) and the new-leader timeout (client.rs, test_new_leader_timeout_disconnects). No test drives ClusterError::Timeout.

Limitations

  • No dynamic membership (static cluster only).
  • No snapshot/recovery integration.
  • No TLS/mTLS at the Aeron transport layer.
  • The cluster_codec_types module is #[doc(hidden)] and not stable API.
  • Ingress is always an exclusive publication, and the client does not expose its raw publication or subscription.
  • After leader loss the old ingress publication stays open until the new leader’s replaces it or the client is dropped (Java closes it at once); offers are refused by state meanwhile.
  • A failed new-leader publication add is reported once and not retried (Java retries a RESOURCE_TEMPORARILY_UNAVAILABLE add).
  • clientInfo is name=<client name> ergo-aeron-cluster <version>, and the default client name is cluster-client (Java: name=<name> version=<v> commit=<sha>, default name empty).

Cluster HA orderbook

Claim-based Cluster publishing with an HA-aware L2 book. The publisher sends complete L2 images, never deltas, through try_claim. Each image carries the publisher’s leadership term (epoch) and a sequence that orders images within that term.

The follower accepts an image only while its session is up, only when the epoch is at least the highest term seen (session terms reported and epochs already applied), and only when it is newer than the last image of the same epoch. A rejected frame changes nothing. A sequence gap within an epoch is applied and counted, because the image is complete. From the first observed session loss (the client leaves Connected, or NewLeader arrives) the book serves nothing until an image from the new term is accepted, so replays and recovery snapshots delayed from the old term cannot restore it.

  • Offline pipeline (ha_offline_pipeline): claim, encode and decode without a live cluster, covering replayed old frames, gaps, reconnects and delayed recovery snapshots.
  • Kill-leader test (ha_kill_leader): kills the leader of a three-node Java cluster, checks the book is not serving on every poll from the loss to the recovery, sends old-term frames through the new leader, and checks they are rejected before a new-term snapshot restores the reference image (requires the Java harness).

Animation, in words: a LeadershipAwareBook starts not serving (NotReady), and live_image() returns None. A term-1 snapshot at seq 10 installs bid 5.00 / ask 5.01 without any checks and starts serving. Increments 11 and 12 each pass three checks (serving, same term, seq = last_seq + 1); the sample then moves the caller’s bids and asks Vecs in whole and frees the old ones. Seq 14 fails the sequence check with SequenceGap { expected: 13, got: 14 }: serving stops at once and the last image stays only behind frozen_image(), for debugging. A NewLeaderEvent calls on_leadership_release, which sets the reason to LeadershipRelease and keeps the term. The missing seq 13, sent to apply_increment, is DroppedNotServing after one compare, as it would have been at any point since the gap. A term-2 snapshot (bids 5.10 and 5.09, ask 5.11, as in the kill-leader test) replaces the image whole and serving resumes. A late term-1 increment then fails the term check (TermMismatch { book_term: 2, msg_term: 1 }) and serving stops again until the next snapshot. Terms, sequences and the increments’ levels are illustrative; the outcomes follow ha_book.rs. On the wire path, BookFollower::on_app_payload treats any book that arrives while not serving as a snapshot, so there increments are never dropped, only replaced by the next full book; and the term passed there is the listener’s current term, not one carried by the message, so the term check guards direct callers that know each message’s term. The costs shown are compares and field writes counted in the code; this sample has no recorded timings.

Source: samples/cluster-ha-orderbook/src/

# Service-free
cargo test --manifest-path samples/cluster-ha-orderbook/Cargo.toml \
  --lib --test ha_offline_pipeline

# Full harness (needs Java)
just fetch-aeron-jars
cargo test --manifest-path samples/cluster-ha-orderbook/Cargo.toml \
  --features test-harness

Cluster RFQ

RFQ / auction protocol codecs with cluster-backed examples. Demonstrates e-sniping timer, auction state machine, and multi-participant message flows over Aeron Cluster.

  • rfq_client: sends RFQ, receives quotes, places order.
  • auction_client: auction lifecycle with e-sniping.
  • rfq_roundtrip: encode/decode parity for all RFQ message types.

Source: samples/cluster-rfq/

cargo build --manifest-path samples/cluster-rfq/Cargo.toml --examples
cargo run --manifest-path samples/cluster-rfq/Cargo.toml --example rfq_roundtrip

ergon-tune

ergon-tune checks a Linux host’s low-latency settings. Each finding says what is wrong, the exact fix, and its evidence: an archived A/B where one exists (evidence), otherwise the kernel’s, Kubernetes’, Aeron’s or a vendor’s documentation and “not measured here”. It changes nothing. Call the checks from your own process, or run the ergon-tune command on the node (where).

AI assistance: like the rest of ergon, this crate was written with heavy AI assistance (disclosure). It is not production-ready.

[dependencies]
ergon-tune = { version = "0.1", features = ["nic"] }   # `nic` adds N1–N5

Glossary

In brackets: the check (T1–N4). Times are in µs.

termwhat it ispros / cons, or when it matters
check, findingA check tests one host (T1–T27, K1–K7) or NIC (N1–N5) setting. A finding is a check that fired, with its fix.Data it cannot read gives unknown, never a warning.
busy-spinning threadA thread that loops on one CPU and never sleeps.Never waits to wake up, but takes a whole CPU. Anything else that runs there pauses it.
hot, housekeeping CPUHot: a CPU a thread busy-spins on. Housekeeping: any other CPU.Move the kernel’s work and interrupts to housekeeping CPUs.
p50, p99, p99.9, p99.99, maxThe median; the slowest 1 in 100, 1,000 or 10,000; the slowest of all. The high ones are the tail.Host noise shows in the tail and max; the p50 often hardly moves.
loop gapA pause seen by a loop that only reads the clock (the TSC, the CPU’s time-stamp counter).Shows how often something took the CPU, and for how long.
interrupt (IRQ)A device or timer stops the CPU to run a kernel handler.On a hot CPU, the loop waits for the handler.
timer tickThe kernel’s regular timer interrupt, CONFIG_HZ times a second.nohz_full stops nearly all of it on hot CPUs (T1).
isolcpusA boot option that keeps other tasks off the listed CPUs.Alone, the tick stays on.
nohz_fullA boot option that stops nearly all timer ticks on the listed CPUs while one task runs there.Use it with isolcpus (T1).
rcu_nocbsA boot option that moves RCU callbacks (the kernel’s deferred clean-up work) off the listed CPUs.Part of T1’s boot line. Not measured alone.
IRQ affinityThe CPUs an interrupt may run on. irqaffinity sets the boot default; /proc/irq/<n>/smp_affinity_list sets one interrupt’s.NIC interrupts on the loop’s CPU cost the tail (T2).
SMT siblings (hyperthreads)Two hardware threads that share one core.A busy sibling, such as an io_uring SQPOLL thread, shares the loop’s core (T10). Graviton, AWS’s Arm CPU, has no SMT.
real-time scheduling (SCHED_FIFO, SCHED_RR)Runs a thread ahead of all normal ones. RT throttling caps it at 0.95 s a second by default.Its CPU’s tick stays on; the latency A/B was inconclusive (T7).
CPU quota (CFS quota)A cgroup’s CPU limit: its threads may run for the quota in each period (100 ms by default). Kubernetes sets one from a container’s CPU limit, docker run --cpus too.A busy-spinning thread runs at the cap: when the cgroup’s threads use the quota up, the kernel stops all of them until the period ends (T9).
throttled, nr_throttledA cgroup stopped because its quota ran out. nr_throttled in its cpu.stat counts the periods it happened in.Should not grow for a busy-spinning container. cpu.stat.local also counts a parent’s (a pod’s) quota (T9).
CPU idle states (C-states), frequencyHow deeply an idle CPU sleeps, and how fast it runs.Deeper sleep saves power but wakes later. Idle depth is checked for the IRQ CPUs and a hot CPU that sleeps (T20), the frequency governor for every CPU (T25).
transparent hugepages (THP)The kernel’s own 2 MiB pages: always, or where the app asks (madvise). khugepaged builds them in the background.khugepaged works in the background, under madvise too (on the regions that asked). Not measured with archived data (T3).
Aeron directoryWhere Aeron, the messaging library, keeps its buffers as memory-mapped files.On a disk filesystem, the kernel writes them back to disk (T4).
media driverAeron’s process that moves messages between the network and the applications, through the Aeron directory.A media driver should run these checks before it starts (Component::Md).
tmpfs, hugetlbfsFilesystems held in memory. /dev/shm is tmpfs; hugetlbfs uses reserved 2 MiB pages.T4 wants the Aeron directory on one: nothing is written back to disk.
NUMA nodeA group of CPUs and the memory nearest them. Large hosts have several.A NIC on another node makes every packet cross between nodes (T6). Not measured.
automatic NUMA balancingThe kernel unmaps pages to see which CPU uses them, and moves them closer.Each unmap gives a pinned thread a page fault: a stop to map the page back (T5). Not measured.
kernel UDPUDP through the kernel’s network stack and sockets. Plain: interrupt-driven, no busy polling.No setup.
interrupt-drivenPackets reach the socket through the NIC’s interrupt, not busy polling.Each packet waits for an interrupt (and any moderation delay: N1).
NIC receive queueA lane the NIC puts arriving packets on. Each has its own interrupt.After every reset, ENA puts queue i’s interrupt on CPU i, isolated CPUs included (T2).
interrupt moderation (rx-usecs)The NIC waits up to rx-usecs µs so one interrupt covers several packets.Fewer interrupts, later packets (N1).
adaptive RX moderationThe driver re-tunes that wait by itself, from a kernel worker.It runs on the CPU that polls the queue: a busy-polling loop’s own CPU (N1).
busy pollingA socket read polls the NIC queue itself instead of sleeping until an interrupt.Per socket with SO_BUSY_POLL; the global sysctls reach every socket on the host.
deferred interrupts (napi_defer_hard_irqs, gro_flush_timeout)The kernel keeps the NIC’s interrupts off and polls from a timer instead, so a busy poller can take the packets.With no busy poller, packets wait for the timer (N2).
RX ringThe NIC’s buffer for arriving packets: how many it can hold.Too small drops bursts (N4).
NIC resetThe driver restarts the NIC: a device reset, ethtool -G or -L, a NIC back from DPDK.On ENA it undoes T2 and N1: re-apply at each link-up. Checks re-run when carrier_changes moves.
ENAAWS’s virtual NIC (Elastic Network Adapter) and its Linux driver.N1 checks its adaptive moderation.
ethtoolLinux’s tool for NIC settings: -C moderation, -G ring sizes, -L queue counts.N1, N4 and N5 read the same settings over netlink (a kernel socket API), without root.
virtual function (VF)A slice of the physical NIC given to a VM (SR-IOV), so traffic bypasses the hypervisor’s software path.Without it, traffic takes the hypervisor’s slower software path (N3).
DPDKA library that drives the NIC from user space, skipping the kernel.Its process needs the NIC pair (T24) and its own isolated cores.
SQPOLL threadAn io_uring kernel thread that runs the ring’s requests, so the loop makes no system calls. Pin it to a CPU of its own.It spins, so its CPU is hot: T1 and T8 check it.
sysfs, /procFiles under /sys and /proc where the kernel shows its settings.Most checks only read these, so they also run on a copied tree (Host::at).
NAKAn Aeron receiver’s request to resend lost data.NAKs in bursts with kernel busy polling: check the RX ring (N4).
open loopEach message is timed from when it was due, not when it was sent.A stall counts against every message it delays.
CLOCK_REALTIMEThe kernel’s wall clock: UTC stamps, kernel and NIC timestamps. A time daemon disciplines it.A pod shares the node’s: fix time sync on the node (T11).
PTP hardware clock (PHC)A NIC’s or hypervisor’s clock (/dev/ptp0, or ENA’s ptp_ena) that chrony can lock CLOCK_REALTIME to (refclock PHC).Tighter than NTP over the network; needs the device on the node (T11).
unbound workqueueKernel work not tied to one CPU (writeback, reclaim, driver work), run by kworker/u threads on the CPUs in /sys/devices/virtual/workqueue/cpumask.On a hot CPU it pauses the loop (T13).
memory compactionThe kernel moves pages to make large free blocks: on demand, or in the background (kcompactd, vm.compaction_proactiveness).A moved page faults on its next touch, locked pages too unless vm.compact_unevictable_allowed is 0 (T14).
kprobe, ftrace hook, BPF programCode the kernel runs at a function or event: a probe’s handler, a tracer, a loaded BPF program.Runs on whichever CPU calls the function, hot ones included (T16).
KSMKernel same-page merging: ksmd merges identical pages of memory that asked for it.A write to a merged page takes a copy-on-write fault (T17).
stealTime the hypervisor ran something else while a vCPU had work (/proc/stat).The loop stands still; the fix is outside the guest (T18).
page faultThe thread touched a page the kernel has not mapped: minor (no I/O) or major (waits for I/O).Each stops the thread; a warmed, locked loop takes none (T19, FaultWatch).
clock sourceThe counter the kernel keeps time with (current_clocksource): tsc, arch_sys_counter, or hpet, acpi_pm.Only the counter (or a hypervisor’s view of it) is read without a system call (T12).

Why check the host

  • A busy-spinning thread loops on one CPU and never sleeps. It loses time only when something takes that CPU: a timer tick, an interrupt (IRQ), a kernel thread, a busy hyperthread on its core.
  • Those pauses set the tail: p99.99 (the slowest 1 in 10,000) and the max.
  • Each comes from a host setting, and a reboot, a new image or a NIC reset can undo it. Check at start-up and again later.

What it checks

checksettingwhy it matters
T1CPU isolation: isolcpus, nohz_full, irqaffinityisolcpus keeps other tasks off the loop’s CPU. nohz_full stops its timer tick, an interrupt CONFIG_HZ times a second. irqaffinity sends new interrupts elsewhere. isolcpus alone leaves the tick on.
T2NIC interrupt placementEach NIC receive queue raises interrupts. On the loop’s CPU, the kernel runs the handler instead of the loop.
T3transparent hugepages (THP)The kernel thread khugepaged merges small pages into 2 MiB pages in the background. Its lru_add_drain_all ran a kworker on an isolated spin CPU (nri-shared-cpus lab).
T4the Aeron directory’s filesystemAeron, the messaging library, keeps its buffers in memory-mapped files in one directory. On a disk filesystem the kernel writes them back to disk.
T5automatic NUMA balancingOn a host with several memory nodes, the kernel unmaps pages to see which CPU uses them, so pinned threads take page faults.
T6the NIC’s NUMA nodeA NIC on another node makes every packet cross between the sockets.
T7real-time schedulingSCHED_FIFO or SCHED_RR keeps the CPU’s tick on. RT throttling (the kernel’s cap on real-time threads, 0.95 s of each second by default) can take the CPU away.
T8SMT siblings, shared CPUsTwo busy threads on one CPU take turns. Two hyperthreads share one core’s execution units.
T9CPU quota (a container’s CPU limit)A cgroup with a quota may use only that much CPU time per period. A busy-spinning thread uses its CPU all the time, so it runs at the cap, and the kernel stops the whole container when the cap is reached. On Kubernetes 1.33+ the kubelet drops the quota itself for a container with exclusive CPUs; never turn it off for the whole node.
T10SMT (hyperthreading) on, x86One Kubernetes cpu: 2 is one physical core, not two. A busy sibling slows the loop. Turn SMT off on the node: EKS/EC2 "CpuOptions": {"CoreCount": <the type's cores>, "ThreadsPerCore": 1} (not on bare metal, or on T2, C7a, M7a, R7a, Apple silicon Mac or Graviton), self-managed nosmt or echo off > /sys/devices/system/cpu/smt/control before the kubelet (then delete its cpu_manager_state). Graviton and arm64 pass: one vCPU is one physical core.
T11how CLOCK_REALTIME is keptUTC stamps are only as good as CLOCK_REALTIME, and CLOCK_MONOTONIC is slewed with it. PTP-grade (chronyd locked to a PHC, or phc2sys) is ok. NTP-disciplined or unsynchronised warns with the refclock PHC line for the host’s PHC; so do a correction still being slewed out, an error bound over 1 ms and a pending leap second. In a pod the daemons and chronyd’s port are usually out of sight: what cannot be seen is unknown, never a warning, but the kernel’s own state (adjtimex) is read there too.
T12the kernel’s clock sourcetsc or arch_sys_counter is read through the vDSO; kvm-clock and Hyper-V’s TSC page are too, where the hypervisor marks them stable (info). hpet or acpi_pm has no vDSO read: every UTC stamp and Aeron clock read is a system call.
T13the unbound workqueue cpumaskkworker/u threads run unbound kernel work on any CPU in /sys/devices/virtual/workqueue/cpumask. nohz_full keeps hot CPUs out of it at boot; a boot without it, or a later write, puts them back. Warn.
T14memory compactionvm.compaction_proactiveness above 0 compacts in the background; vm.compact_unevictable_allowed 1 moves locked pages too, so mlockall does not pin them. A moved page faults on its next touch. Info: compaction on demand still runs.
T15other processes’ tasks on hot CPUsA task of another process whose Cpus_allowed_list includes a hot CPU can be woken there. This process’s threads, zombies and kernel threads are not asked. In a pod’s own PID namespace the node’s tasks cannot be seen: unknown, unless one it can see fires. Warn.
T16kprobes, ftrace hooks, BPF programsEach runs inline on the CPU that calls what it is attached to. Read from debugfs, tracefs and /proc/kallsyms; unprivileged, or with bpf_jit_harden on, these are unreadable or hide BPF programs: unknown. Info.
T17KSM/sys/kernel/mm/ksm/run 1: ksmd merges pages, and a write to a merged page takes a copy-on-write fault. Warn.
T18steal on hot CPUs/proc/stat’s steal since boot: the hypervisor ran something else while the vCPU had work. 0 also when the hypervisor does not report steal. Info.
T19page faults on a hot threadFaultWatch reads the thread’s minflt and majflt again while it runs. Any fault since the last check warns.
T20idle depth of the CPUs that take the NIC interruptscpuidle states each IRQ CPU may enter (enabled, within pm_qos_resume_latency_us). One with exit latency above 1 µs (C1E, C6) warns: each interrupt waits for the wake. Info for acpi_idle stopping at C1 and for a hot CPU that sleeps (the conductor); ok without a cpuidle driver (Graviton).
T21TCP autocorkingnet.ipv4.tcp_autocorking in the process’s network namespace. On: a small send waits for the previous one’s transmit to complete, TCP_NODELAY or not. A warning for latency-sensitive TCP, info otherwise. Unknown under ergon-tune --root: the tree’s /proc/sys/net need not be the application’s namespace.
T22Aeron affinity namesAeron’s affinity settings named as before 1.54 (AERON_DRIVER_CPUSET_AFFINITY, AERON_DRIVER_CPUSET_WARNINGS_AS_ERRORS) in the environment. Aeron 1.54 ignores them: rename to AERON_THREAD_AFFINITY_USE_CPUSET_OFFSETS and AERON_THREAD_AFFINITY_FAIL_ON_VALIDATION_ERRORS.
T23Aeron on 2 MiB pagesAERON_DIR on hugetlbfs without AERON_FILE_PAGE_SIZE=2097152 and AERON_TERM_BUFFER_SPARSE_FILE=false. The shared-CPU plugin sets both from hugepages.ergon.io/<container>: "2M". The process still sets AERON_DIR. Address, gateway and PCI stay unset.
T24a DPDK NIC pairFor a caller on DPDK, which needs a NIC device plugin, not shipped here, to inject the pair: RUSTERON_DPDK_SENDER_{PCI,IPV4_CIDR,GATEWAY} missing, empty or unparsable, warn with the exact keys. All three set: the finding prints the copy lines built from them (copied, never guessed). Not on DPDK, or no pair granted: ok: no device plugin granted a pair, not a guessed address. Reads only: it exports nothing, binds no NIC, sets no AERON_DIR, and is never unknown.
T25the CPU frequency governorcpufreq/scaling_governor on every online CPU that has one. Another governor than performance drops the frequency between bursts, so a hot core’s next busy-spin pays the ramp. Warn. Fix (node): cpupower frequency-set -g performance or cpufreq.default_governor=performance. No cpufreq on arm64 (Graviton): ok; on x86: unknown.
T26the instance family’s CPU layoutWith --family (c7i, c7a, c8g, c9g): the host’s vendor and threads per core match the family, the pinning map’s CPUs are online, and no two of its busy threads share a physical core. A map built for another family measures slow instead of failing, so a mismatch warns and an unreadable vendor or layout is unknown; both stop require. Fix: one CPU per physical core (named in the finding), ThreadsPerCore: 1 on c7i; on Kubernetes the kubelet’s full-pcpus-only (node) and whole-core requests (pod spec).
T27the listen ports vs the kernel’s ephemeral port rangeA caller whose application listens on ports declares them (t27_ephemeral_overlap(host, listen)). A listen range that overlaps net.ipv4.ip_local_port_range and is not covered by net.ipv4.ip_local_reserved_ports warns: the kernel can hand a listen port to an outgoing connection, so the listening app then fails with Address already in use. Fix: move the listen range below the ephemeral range, or reserve the overlap (sysctl -w net.ipv4.ip_local_reserved_ports=<reserved-line>). Like T24, the caller feeds it and the ergon-tune command does not run it. A listen range that ends before it starts, or a sysctl it cannot read, is unknown, never a warning.
K1the pod’s QoS classAnything but Guaranteed gets a CPU limit and shares CPUs; the loop runs at the cap or with a neighbour. Fix (pod spec): resources.requests = resources.limits.
K2exclusive CPUsThe shared pool means other pods land on the loop’s CPU. Fix (node): kubelet cpuManagerPolicy: static (with full-pcpus-only on x86); fix (pod spec): whole-CPU requests in a Guaranteed pod.
K3the loop’s SMT siblingA sibling in another pod is a busy neighbour (the T10 numbers). Fix (node): turn SMT off; fix (pod spec): ask for whole cores so both siblings come together.
K4a CPU for the helper threadsOne CPU means the handshake and the warning thread share the loop’s core. Fix (pod spec): cpu: 2, or name ERGON_SHARED_CPUS/ERGON_HELPER_CPUS.
K5capabilitiesBusy polling needs CAP_NET_ADMIN, SCHED_FIFO CAP_SYS_NICE, mlockall CAP_IPC_LOCK (or RLIMIT_MEMLOCK). Warns only for what the caller says it uses (Needs). Fix (pod spec): securityContext.capabilities.add.
K6memory.highAt memory.high the kernel reclaims and throttles the cgroup. Fix (pod spec): drop memory.high (set requests = limits); fix (node): less load on the node.
K7the NIC’s NUMA nodeSame as T6, for a pod. Runs only when the caller names the NIC (Needs::with_nic). Fix (node): kubelet topologyManagerPolicy: single-numa-node; fix (pod spec): ask for CPU and device together.
N1ENA adaptive RX moderationModeration makes the NIC wait so one interrupt covers several packets. ENA re-tunes that wait from a kernel worker on the CPU that polls the queue: a busy-polling loop’s own CPU.
N2deferred interruptsnapi_defer_hard_irqs and gro_flush_timeout hold interrupts back so a busy-polling socket (one whose reads poll the NIC queue) can take the packets. With no busy poller, packets wait for the timer.
N3a virtual function (VF) under a synthetic NIC driver (checked for hv_netvsc)Without its VF, traffic takes the hypervisor’s slower software path.
N4NIC receive (RX) ringHow many packets the NIC can hold. Too small, and it drops packets in bursts.
N5ENA interrupts with moderation offWith N1’s setting (adaptive RX off) each packet interrupts at once; on the receiver’s own CPU that pauses the loop per packet. Warn on Graviton, info elsewhere (T2 warns on the placement too). Fix (node): pin them to a spare CPU outside every pod’s exclusive CPUs, or turn moderation back on.

Not checked: the idle depth of CPUs other than the IRQ CPUs and a hot CPU that sleeps (T20).

Symptom, check, fix

symptomcheckfix
tens of thousands of loop gaps a minute; about 1,000 timer interrupts a second on the loop’s CPUT1boot with isolcpus=nohz,domain,managed_irq,<hot> nohz_full=<hot> rcu_nocbs=<hot> irqaffinity=<housekeeping>
hundreds of loop gaps a minute; burst p99 upT2echo <housekeeping> > /proc/irq/<n>/smp_affinity_list, again after every NIC reset
THP always or madviseT3echo never > /sys/kernel/mm/transparent_hugepage/enabled, or boot with transparent_hugepage=never
Aeron directory on ext4, xfs or overlayfsT4/dev/shm (in a pod: a memory-backed emptyDir sized for Aeron’s files), or a sized 2 MiB hugetlbfs with AERON_FILE_PAGE_SIZE=2097152: on the node mount -t hugetlbfs -o pagesize=2M,size=1G none /mnt/huge, in a pod the nri-latency-pods plugin’s $ERGON_HUGEPAGES_DIR
page faults on pinned threads; several NUMA nodesT5on the node: sysctl -w kernel.numa_balancing=0
NIC and hot CPUs on different nodesT6pin the threads to the NIC’s node, or use a NIC on theirs
a real-time thread on the loop’s CPUT7chrt --other -p 0 <tid>, on an isolated CPU
two busy threads on one CPU or coreT8pin them to separate cores; leave the sibling idle
stalls of milliseconds in a container; nr_throttled in /sys/fs/cgroup/cpu.stat growsT9Kubernetes 1.33+: cpuManagerPolicy: static, a Guaranteed pod and whole-number CPU requests, so the kubelet drops the quota itself. Never cpuCFSQuota: false: it removes every pod’s CPU limit on the node (checklist)
a cpu: 2 pod runs like one core; p50 up with work on the loop’s siblingT10, K3turn SMT off on the node (EKS CpuOptions: ThreadsPerCore: 1, or nosmt)
a Burstable pod, the shared CPU pool, or a CPU for helpers missingK1, K2, K4Guaranteed with requests = limits; the kubelet’s static CPU manager; cpu: 2
AWS: p99.99 high with a busy-polling loopN1ethtool -C <if> adaptive-rx off rx-usecs 0, again after every reset
packets on sockets that do not busy-poll held for gro_flush_timeoutN2echo 0 > /sys/class/net/<if>/napi_defer_hard_irqs; echo 0 > /sys/class/net/<if>/gro_flush_timeout
VF missing or downN3node-level: enable the virtual function (SR-IOV) under the synthetic NIC driver (hv_netvsc; N3 checks that driver)
NIC drops and NAKs in bursts with kernel busy pollingN4ethtool -G <if> rx 4096 (on ENA this resets the NIC: re-pin, turn adaptive-rx off again)
fine after boot, worse laterT2, N1an ENA reset undid them: re-apply from a link-event hook
cross-host one-way latencies drift or jumpT11on the node: chrony refclock PHC /dev/ptp_ena poll 0 delay 0.000010 prefer (AWS, ENA PHC enabled) or refclock PHC /dev/<device> on another host’s PHC
clock reads slow; current_clocksource is hpetT12find why the kernel left the counter: dmesg | grep -i clocksource. Force tsc=reliable only on hardware qualified across cores, never on a VM
kworker/u threads on the loop’s CPUT13on the node: echo <housekeeping mask> > /sys/devices/virtual/workqueue/cpumask, or boot with nohz_full
page faults on a pinned, locked threadT14, T17, T19on the node: sysctl -w vm.compaction_proactiveness=0 vm.compact_unevictable_allowed=0; echo 2 > /sys/kernel/mm/ksm/run; in the process: mlockall and touch every buffer before the loop
another program’s threads on the loop’s CPUT15boot with isolcpus=domain,<hot>; systemd CPUAffinity=<housekeeping>; taskset -apc <housekeeping> <pid>; kubelet reservedSystemCPUs
interrupt-driven receive slow at low rates on Intel ; intel_idleT20per IRQ CPU echo 1 > /sys/devices/system/cpu/cpu<N>/cpuidle/state<i>/disable for each state past C1, or echo 1 > …/cpu<N>/power/pm_qos_resume_latency_us; at boot intel_idle.max_cstate=1 (every CPU). Node settings: a pod cannot write /sys, and holds /dev/cpu_dma_latency only privileged
small TCP sends late though TCP_NODELAY is set; nstat TcpExt TCPAutoCorking growsT21sysctl -w net.ipv4.tcp_autocorking=0 in the sender’s network namespace: a pod’s securityContext.sysctls (an unsafe sysctl: kubelet --allowed-unsafe-sysctls), the node for hostNetwork
a DPDK process starts without the NIC pair, or with an unparsable oneT24the NIC device plugin (not shipped here) must inject the three RUSTERON_DPDK_SENDER_* keys; the finding prints the copy lines built from them
a listening app fails to bind with Address already in use though the port is not in useT27move the listen range below net.ipv4.ip_local_port_range, or reserve the overlap: sysctl -w net.ipv4.ip_local_reserved_ports=<reserved-line>
stalls no host setting explainsT16, T18bpftool prog show and /sys/kernel/debug/kprobes/list (root) for the owners of instrumentation; for steal, an instance whose vCPUs are not shared, or bare metal

Each finding carries the fix for that host, with its real CPU lists and IRQ numbers. T1 with the loop on CPU 2 of 8: isolcpus=nohz,domain,managed_irq,2 nohz_full=2 rcu_nocbs=2 irqaffinity=0-1,3-7.

Evidence per check

Each finding’s evidence field names the kernel, driver, Kubernetes or vendor source it rests on. T3’s effect is also traced in this repository: the nri-shared-cpus lab saw khugepaged’s kworker on an isolated CPU.

checkevidencestatus
T1Documentation/timers/no_hz.rst, kernel-parameters.txtnot measured here
T2ENA’s driver source (ena_setup_io_intr: queue i’s IRQ on CPU i)not measured here
T7Documentation/scheduler/sched-rt-group.rstnot measured here
T8, T10, K3siblings share one core; AWS CpuOptions, kernel-parameters.txt (nosmt)not measured here
N1, N5ENA’s driver source (ena_up enables adaptive moderation); AWS Graviton performance runbooknot measured here
T20Documentation/admin-guide/pm/cpuidle.rst, intel_idle.rstnot measured here
T25Documentation/admin-guide/pm/cpufreq.rstnot measured here
T26AWS instance-type families (ThreadsPerCore); ABI/testing/sysfs-devices-system-cpu (thread_siblings_list)not measured here
T27Documentation/networking/ip-sysctl.rst (ip_local_port_range, ip_local_reserved_ports); the kernel’s outgoing-connection port selectionnot measured here
T21net/ipv4/tcp.c tcp_should_autocorknot measured here
T3nri-shared-cpus labtraced
N3Hyper-V/Azure accelerated-networking documentation (the check applies to any Hyper-V hv_netvsc host)not measured here
T4, T5, T6, T9, T11–T19, T22–T24, K1, K2, K4–K7, N2, N4kernel, Kubernetes, Aeron, chrony, AWS documentationnot measured here

Where the checks run

The callers are not in this repository: each row is what that kind of caller should run.

callercheckswhen
a network I/O loop (Component::Io)T1 and T8 on the loop’s CPU (and an SQPOLL CPU); T7 on the calling thread; T9, T10; T3 as info; T24 on DPDK; K1–K6 inside a pod; T2, N1, N2, N3, N5 on each connection’s egress NIC; T19 on the polling threadat start; the NIC checks again after a NIC reset; T19 every few seconds from housekeeping
a media driver (Component::Md)T1, T3, T4, T5, T7, T8, T9, T10, T22, T23; T24 on a DPDK port; T2 and T6 on the data NICs; on the socket transport also N1, N2, N5, and N4 with busy pollingbefore the driver starts; N1 and T2 again after a NIC reset
your own busy loop (Component::Rt)any of them: T1, T3, T4 (the directory it connects to), T5, T7, T8, T9, T10, T11, T12, T13–T18, T21, T22, T25, T26 (with its instance family), T27 (with its listen port ranges); K1–K7 inside a pod; on a kernel NIC also T2, T20, N1, N2, N3, N5; ThrottleWatch, ClockWatch, FaultWatchbefore the loop; the NIC checks again when the NIC’s carrier_changes moves; ThrottleWatch::check, ClockWatch::check and FaultWatch::check every few seconds from housekeeping
Before the loop
once
Hot loop
Housekeeping
every few seconds
On a NIC event
Start-up checks, the ones the caller picks (the table on this page lists them per caller)
K1–K7 only inside a pod: KUBERNETES_SERVICE_HOST, the service-account mount or a kubepods cgroup path
No host check is ever called here: the busy-spinning thread only does its work
ThrottleWatch::check
T9: CPU quota stalls
FaultWatch::check
T19: page faults on the thread
ClockWatch::check
T11 verdict or T12 clock source changed
NIC carrier_changes moved (an interface reset)
The NIC checks run again (T2, N1, …)
ERGON_HOST_CHECKS, any case
unset, on, warn → on
off → off
require → require
anything else → HostCheckError::Invalid
ergon-tune CLI exits
0 reported · 1 --require refused · 2 usage error
Status of
one finding?
Ok
prints nothing
A warning (Finding + Warn)
prints <prefix> warning: … (ERGON_HOST_CHECKS=off silences host-check warnings); dropped under off
Info (Finding, severity Info)
prints <prefix> info: … under every policy; never refuses
Unknown(reason)
prints <prefix> info: … under every policy
Refuses the start
HostCheckError::Warnings{count, ids}
Id one of the 23
subsystem ids?
Allowed through
T3–T6, T11, T13–T21, T25, K6, K7, N1–N5, M4
Refuses the start: fails closed, a caller’s own ids too
A · When the checks run
B · What ERGON_HOST_CHECKS does with one finding
under require
under require
yes
no
Host checks: when they run, and what ERGON_HOST_CHECKS does with each result

Read ERGON_HOST_CHECKS through HostCheckPolicy: on (default), off (no warning line; the results stay) or require (a warning, or an unproven proof check, stops the start). Skip a check by not calling it.

Every printed warning line ends with (ERGON_HOST_CHECKS=off silences host-check warnings). The K checks run only inside a pod (the kubepods cgroup path, the service-account mount, or KUBERNETES_SERVICE_HOST) and each says whether its fix is in the pod spec or on the node.

require is a readiness gate, not a blanket refusal. It refuses on a warning (a check fired) and on a check that could not prove a property of this pod or process (its CPUs are its own, they are isolated, there is no CPU quota, its helpers have a core, its pinning map fits the declared instance family) because starting on an unproven claim is the false pass those checks exist to stop. An unknown of a check whose subsystem the node may not have (memory.high, a NUMA node, a NIC knob, THP) is printed and allowed through: that is a real host, and refusing there would stop every start on it. unknown_stops_require(id) says which: T3, T4, T5, T6, T11, T13-T21, T25, K6, K7, N1-N5 and M4 do not block; every other id does, a caller’s own included.

Two consequences under require:

  • T10 warns on every x86 host with SMT on, so require refuses it, including the SQPOLL-on-sibling layout T8 accepts.
  • K2 proves exclusive CPUs only from an isolated or root cpuset partition, or a matching cpuset.cpus.exclusive. The kubelet’s static CPU manager writes neither, so a stock Guaranteed pod is K2 unknown and refused. The nri-latency-pods plugin’s isolated partition (Linux 6.7+) passes it.

Limits:

  • Name the loop’s CPU. T1, T8 and T2 need it in the HotSet: pin the thread first, then pass its CPU.
  • A media driver knows its data NICs only if its configuration names them; pass them to T2, T6 and the N checks.
  • Print each finding once on stderr, never from a busy thread.
  • In a pod the NIC checks report unknown: run them on the node (Kubernetes). T9 reads the container’s own cgroup; the pod’s quota shows only in cpu.stat.local (Linux 6.6+), which ThrottleWatch reads.
  • In CI, run them on a captured /sys and /proc tree: Host::at(dir).

Check a node first: the ergon-tune command

Before deploying, run the checks on the node, or in a pod that mounts the node’s root, and fix what they report:

cargo install ergon-tune
ergon-tune --hot 2-7 --nic ens6 --tcp           # on the node
ergon-tune --root /host --hot 2-7 --require     # a pod with the node's / at /host
OptionMeaning
--hot CPUSthe busy-spinning CPUs; default the node’s isolated ones
--nic NAME|PCIa data NIC (ens6) or DPDK port (0000:00:06.0): adds T2, T6, T20; repeatable
--family NAMEthe instance family (c7i, c7a, c8g, c9g): adds T26, which checks the layout and the --hot map against it
--tcpthe app sends latency-sensitive TCP: T21 warns
--busy-pollsockets busy-poll: K5 asks for CAP_NET_ADMIN
--component io|md|rtwho spins, for T3’s severity (default md)
--root DIRcheck a mounted tree instead of /; T9 (CPU quota) is not checked there, since /proc/self is ergon-tune itself: the app checks its own quota at start
--allprint the checks that passed too
--requireexit 1 where ERGON_HOST_CHECKS=require would refuse a start, or when there are no hot CPUs to check

Each line is a finding (WARN, info, UNKNOWN, ok) with its evidence and its fix; a summary line ends the output. Exit status: 0 reported, 1 refused (--require), 2 usage.

Call them yourself

The checks are plain functions. They read files and allocate: call them before the loop or from housekeeping, never inside the loop.

  • Host::system() is the running host. Host::at(dir) is a directory that stands for a host’s /, on any OS.
  • HotSet lists the CPUs your threads busy-spin on, each with a Role (Loop, Sender, SqPoll, …), so a message names the thread.
  • Component (Io, Md, Rt) is the caller. It sets T3’s severity: warn for Md and Rt, info for Io.
/// Every host check, with `hot` and each interface the host shows.
fn run_all(host: &Host, cpus: &HotSet, interfaces: &[String]) -> Vec<Finding> {
    let mut all = Vec::new();
    all.extend(t1_isolation(host, cpus));
    for c in [Component::Md, Component::Io, Component::Rt] {
        all.extend(t3_thp(host, c));
    }
    all.push(t4_aeron_dir(
        host,
        Path::new("/dev/shm/ergon-tune-live/aeron"),
    ));
    all.push(t5_numa_balancing(host));
    all.push(t7_sched_policy(host, Thread::Current, Role::Loop));
    all.extend(t8_smt_siblings(host, cpus));
    all.push(t9_cpu_quota(host));
    all.push(t10_smt_on(host));
    all.push(t13_workqueue_cpumask(host, cpus));
    all.push(t14_compaction(host));
    all.push(t15_host_tasks(host, cpus));
    all.push(t16_instrumentation(host));
    all.push(t17_ksm(host));
    all.push(t18_steal(host, cpus));
    all.push(t25_frequency(host));
    all.extend(k8s_checks(
        host,
        cpus,
        &Needs::new(Thread::Current, Role::Loop),
    ));
    for i in interfaces {
        let nic = Nic::Interface(i.clone());
        all.extend(t2_nic_irqs(host, &nic, cpus));
        all.extend(t6_nic_node(host, &nic, cpus));
    }
    all
}

The NIC checks need the nic feature. Keep one EthtoolCache::new() for the process: it asks the kernel once per interface, and again only after a reset (when carrier_changes moves). Here i is an interface name:

            let mut v = vec![
                n1_adaptive_rx(&host, &i, &mut cache),
                n3_azure_vf(&host, &i),
                n4_rx_ring(&host, &i, &mut cache),
            ];
            v.extend(n2_deferred_irqs(&host, &i, Some(false)));

(From tune/tests/live.rs, which runs every check against the host it runs on: cargo test -p ergon-tune --all-features.)

functionreturnscost
t1_isolation(&host, &hot)one finding per missing setting per CPUa few sysfs reads
t2_nic_irqs(&host, &nic, &hot)one finding per IRQ that may fire on a hot CPUone directory and two files per IRQ
t3_thp(&host, component)one findinga few sysfs reads
t4_aeron_dir(&host, path)one findingone statfs; unknown on a tree
t5_numa_balancing(&host)one findinga few sysfs reads
t6_nic_node(&host, &nic, &hot)one finding per PCI devicea few sysfs reads
t7_sched_policy(&host, thread, role)one findingone /proc read; Thread::Current from the thread that will spin, or Thread::Task(tid)
t8_smt_siblings(&host, &hot)one finding per shared corea few sysfs reads
t9_cpu_quota(&host)one finding/proc/self/cgroup and a few cgroup files
ThrottleWatch::open(&host), then .check()open: the watch, before the loop; check: a finding when the cgroup was throttled since the last checkcheck: one read of cpu.stat.local, which open opened, and of cpu.stat only after that grew (its read takes a kernel lock); no allocation unless it reports; call it from housekeeping
n1_adaptive_rx, n4_rx_ring(&host, ifname, &mut cache)one findingone netlink exchange per interface per reset (and one family lookup on first use), each with 100 ms send and receive timeouts; unprivileged
n2_deferred_irqs(&host, ifname, busy_polls)one finding per deferring devicesysfs; busy_polls is Some(true) if your sockets busy-poll, None if not known
n3_azure_vf(&host, ifname)one findingsysfs
t11_time_sync(&host, &probe)the verdict’s finding, plus one each for an unsettled clock, a wide bound, a pending leap secondadjtimex, a /proc scan, /sys/class/ptp, ClockBound’s segment, and a chronyd query of at most 50 ms; the pure step is TimeSync::from_observed
t12_clocksource(&host)one findingtwo file reads
ClockWatch::open(&host, &probe), then .check()open: T11 and T12, and the watch, before the loop; check: T11’s findings again when its judgement changed, T12’s when the clock source did, else nonecheck: one adjtimex, one non-blocking receive and send to chronyd (its answer used one check late), ClockBound’s segment and the clock source read again; never waits; no allocation unless a finding changed; update(sample) judges an injected sample
t13_workqueue_cpumask(&host, &hot)one findingone sysfs read
t14_compaction(&host)one findingtwo /proc/sys reads
t15_host_tasks(&host, &hot)one finding, naming up to six processesa /proc scan: two files per task on the host
t16_instrumentation(&host)one findingdebugfs, tracefs and /proc/kallsyms (a few MB)
t17_ksm(&host)one findingone or two sysfs reads
t18_steal(&host, &hot)one findingone read of /proc/stat; cpu_steal(&host) gives each CPU’s counts, to diff two readings
FaultWatch::open(&host, thread, role) (or open_task(&host, pid, tid, role)), then .check()open: the watch, before the loop; check: a warning when the thread faulted since the last checkcheck: one pread of the thread’s stat, which open opened; no allocation unless it reports. Open it with Thread::Current on the hot thread itself, or by thread id from anywhere

A Nic is Nic::Interface("ens5") or a DPDK port, Nic::Pci("0000:00:06.0"). The readers underneath (thread_affinity, carrier_changes, nic_irqs, busy_poll_sysctls, fs_magic, cpu_cgroup, Platform::detect) are public too.

Read a finding

fieldmeaning
idthe check, a string: "T4", "K2", "M1", or a caller’s own
statusFinding: it fired. Ok: fine, or it does not apply here. Unknown(reason): the data could not be read.
severityWarn or Info: how to log a Finding
messagewhat was found, its effect, and the fix
evidencewhere the numbers come from

Display prints one line, T4 warn: <message> (evidence: <where>) or T4 unknown: <message>: <reason>:

#[test]
fn findings_print_as_one_line_each() {
    let f = t4_from(Path::new("/var/lib/aeron"), Ok(FsMagic(0xEF53)));
    let line = f.to_string();
    assert!(line.starts_with("T4 warn: "), "{line}");
    assert!(line.contains("(evidence: "), "{line}");
    assert!(!line.contains('\n'), "{line}");
    let u = t4_from(Path::new("/aeron"), Err(ReadError::NotLinux("statfs")));
    assert!(u.to_string().starts_with("T4 unknown: "), "{u}");
}
  • Warn: fix it.
  • Info: real but minor, such as THP for a network I/O loop or an IRQ whose new affinity takes effect at its next interrupt.
  • Unknown is never a warning: a pod’s network namespace, hidepid, an interface with no device, not Linux. Log it as info.
  • To make warnings fatal, read ERGON_HOST_CHECKS=require through HostCheckPolicy, or test is_warning() in your own start-up.

Alternatives

toolgood atshort ofuse it
tuned profiles (cpu-partitioning, latency-performance)applying isolation, IRQ and power settings; tuned-adm verify checks they stuckdoes not know which threads spin, which NIC they use, or what a setting costs; not measured hereto apply settings, with ergon-tune checking the result
a gap spinner, or the kernel’s osnoise and hwlat tracers (rtla)measuring noise on each CPU, whatever its causesays how much, not which settingto choose quiet cores
provisioning scripts alonesetting everything oncedrift: ENA re-places queue IRQs whenever an interface comes up (ena_setup_io_intr in its driver)with ergon-tune re-checking

Best practices and pitfalls

  • Pin first, then check. Name the CPU the thread is pinned to, not the one it happens to run on.
  • Re-check after every NIC reset. Whenever ENA brings an interface up (a device reset, ethtool -G or -L, a NIC handed back from DPDK), it puts queue i’s interrupt on CPU i, isolated CPUs included, and turns adaptive moderation back on. Re-pin from a link-event hook.
  • N1, busy polling: adaptive-rx off rx-usecs 0. Not measured here.
  • Use THP never, not madvise. khugepaged still runs under madvise (kernel transhuge.rst); the cost is not measured here.
  • No CPU quota on a busy-spinning container. /sys/fs/cgroup/cpu.max should read max 100000, and nr_throttled should not grow while it runs (T9, ThrottleWatch). Set-up: Kubernetes.
  • Graviton has no SMT, so T8 fires there only when two busy threads share one CPU. N2 does not suggest busy polling there.
  • Test your host image. Build a tree with the files your provisioning writes and assert on the findings, as tune/tests/common does for five hosts.
  • Measure your own host. No latency effect of these checks is measured here.

How to apply each setting on AWS, x86 and Graviton: Hosts.

Using ergon-tune

Run ergon-tune on the node and in the pod, before deploying and again with the application running. Fix every WARN, then rerun until none is left, and gate CI or start-up with --require. Every command, flag and exit code below is the ergon-tune binary’s own (tune/src/bin/ergon-tune.rs); the check catalogue is in Host checks.

When to run

whenwherewhy
before deployingon the nodethe boot line and NIC settings (T1, T2, N1) live on the node
at every pod’s start-upinside the podK1–K7 read the pod’s own cgroup and capabilities
with the application runningnode and podname the CPUs your pinned threads use with --hot; T9’s throttling counters grow only under load, and T15’s task scan sees who runs on the hot CPUs when you check
after every reboot or new imageon the noderuntime fixes (sysctl -w, echo into /sys, ethtool) are gone; the checks cannot tell which settings persist
after every NIC reseton the nodeENA re-places each queue’s IRQ (T2) and turns adaptive moderation back on (N1)

Commands

cargo install ergon-tune

ergon-tune --hot 2-7 --nic ens6 --tcp                # on the node
ergon-tune --root /host --hot 2-7 --require          # a pod with the node's / at /host
ergon-tune --hot 2-7 --family c7i --busy-poll --all  # AWS c7i, busy-polling sockets, verbose
flagwhat it does
--hot CPUSthe busy-spinning CPUs (a list such as 2-7); default: the node’s isolated ones. Name them: without hot CPUs the per-CPU checks have nothing to check
--nic NAME or --nic PCIadds T2, T6 and T20 for that NIC; repeatable. A value with two colons and a dot is a PCI address (0000:00:06.0), else an interface name (ens6)
--family NAMEthe AWS instance family, c7i, c7a, c8g or c9g (size optional, c7i.2xlarge): adds T26, which checks the host’s CPU layout and the --hot map against it
--tcpthe app sends latency-sensitive TCP: T21 warns instead of informing. Under --root T21 is UNKNOWN: the tree’s /proc/sys/net need not be the application’s network namespace
--busy-pollsockets busy-poll: K5 asks for CAP_NET_ADMIN
--component io|md|rtwho runs on the hot CPUs, for T3’s severity (default md)
--root DIRcheck a tree mounted from the node (such as /host) instead of /
--allalso print the checks that passed
--requireexit 1 where ERGON_HOST_CHECKS=require would refuse a start
--help, -husage; exits 0

Kubernetes

  • In the pod the K checks run by themselves (they detect the pod). The pod sees its own cgroup and capabilities; each fix names whether it is in the pod spec or on the node.
  • The node’s checks from inside a pod: mount the node’s / read-only at /host and use --root /host. Name the node’s interface with --nic, not the pod’s.
  • Gate start-up: run the same command with --require in an init container or CI job. In your own code, read ERGON_HOST_CHECKS through HostCheckPolicy (off, on/warn, require): require refuses a WARN and an unknown of a check that must prove something about this pod or process; an unknown of a subsystem the node may lack is reported and allowed through.

Reading the output

Each line is a tagged finding; a summary: N warnings, N info, N unknown, N ok line ends the report.

tagmeaningwhat to do
okpassed, or does not apply herenothing; printed only with --all
inforeal but minorfix when convenient
WARNthe setting costs latencyfix it; --require refuses
UNKNOWNthe data could not be readnever a warning; see what it cannot see
exit codemeaning
0reported (also --help)
1--require and the report would refuse a start
2usage error: unknown flag, missing value, bad --component

Privileges

whatprivilege
running the checksnone: they read /sys and /proc, and NIC settings over unprivileged netlink
busy pollingthe application needs CAP_NET_ADMIN; --busy-poll makes K5 warn when it is missing
real-time threads, mlockallCAP_SYS_NICE, CAP_IPC_LOCK (K5, when a library caller declares them)
the fixesroot on the node; a pod cannot write /sys, so fixes are node settings or pod-spec settings

What it cannot see

blind spoteffect
a pod’s virtual interface (a veth has no device behind it)the NIC checks are UNKNOWN in a pod; run them on the node or through --root /host
a virtio NIC’s own interrupts (they belong to its parent PCI device)T2 is UNKNOWN
the node’s tasks from a pod’s own PID namespaceT15 is UNKNOWN
a time daemon outside the pod’s namespacesT11 is UNKNOWN (the kernel’s own clock state is still read)
BPF programs as an unprivileged readerT16 is UNKNOWN
anything but Linux (macOS)the checks that read /sys and /proc are UNKNOWN (“only Linux has them”); per-CPU checks pass only because there is no hot CPU to check

Worked sequence: run, fix, rerun

ergon-tune --hot 2-7 --nic ens6 --family c7i --tcp --busy-poll --all
  1. Read the WARN lines. Each carries the fix for this host, with its real CPU lists and IRQ numbers.
  2. Apply each fix (node or pod spec), then rerun the same command.
  3. Repeat until the summary shows no warnings. info and UNKNOWN may remain; read them.
  4. Put ergon-tune --hot <cpus> --require in CI or an init container, or ERGON_HOST_CHECKS=require in the application’s start-up.
  5. After every reboot, image change or NIC reset, run it again.

Shared CPUs for helper threads (k8s/nri-shared-cpus)

How to install and use k8s/nri-shared-cpus on a Kubernetes node.

A busy-spinning pod gets whole cores of its own from the kubelet. Its helpers (dial, TLS, warnings, Aeron conductors) do not need a whole core, and running them on the loop’s core is what this layout forbids. With the helpers on the shared CPU and the quiet-CPU settings, one Azure Cobalt VM measured the loop at p50 0.02 µs, p99.99 0.03 µs, max 4.81 to 5.52 µs, with 0 involuntary switches a minute; 3.5 to 5.5 µs is the hypervisor’s floor (benchmarks). This is a containerd NRI plugin and a kubelet device plugin that give the pod the node’s shared housekeeping CPUs as well, and start every thread there.

The busy-spin loop keeps its exclusive core. Only sleepy helpers go to the shared CPUs. Never a spinner or SQPOLL there: either takes the CPU from every helper on it.

Source: k8s/nri-shared-cpus/.

Status: published as tag 0.1.6. Anyone can pull the image and the chart. The kind e2e passed at its source. Verified on EKS AL2023 (Kubernetes 1.36, c8g.xlarge) with the same plugin and chart source as published 0.1.2 (85098f8b; 0.1.3 to 0.1.5 leave CPU placement unchanged, 0.1.6 adds the shared-burst resource; not re-run on EKS), built from that source and pushed to the run’s ECR: the NRI socket, nodeadm’s TOML merge, the kubelet drop-in merge, /opt writable, system-node-critical outside kube-system. Latency of the spin loop is measured on one Azure VM. Related projects (credited): k8s/nri-shared-cpus/README.md.

Use the public chart

Do these in order. The chart installs the DaemonSet. It does not prepare the node, and it does not install the hot-pod admission policy.

  1. Prepare the node. Node setup below. Label it ergon.io/shared-cpus=true.
  2. Install. config.sharedCpus is the housekeeping CPU, inside reservedSystemCPUs, and not the IRQ CPU. For the 8-CPU split in that section the value is 0. One Helm release per shared-CPU layout. The three hostContract flags mount the node’s kubelet config, /sys and /proc read-only; the plugin checks every pod labelled ergon.io/latency: hot against them (Node setup).
helm install ergon-shared-cpus oci://ghcr.io/mimran1980/charts/ergon-shared-cpus \
  --version 0.1.6 \
  --namespace ergon-system --create-namespace \
  --set-string config.sharedCpus=0 \
  --set 'config.namespaces={trading}' \
  --set hostContract.kubeletConfig.enabled=true \
  --set hostContract.sys.enabled=true \
  --set hostContract.proc.enabled=true

EKS AL2023 (verified at 0.1.2 on EKS 1.36 c8g.xlarge, containerd 2.3.5, with the same plugin and chart source as published 0.1.2 (85098f8b), built from that source and pushed to the run’s ECR; 0.1.3 to 0.1.5 leave CPU placement unchanged and were not re-run there). nodeadm writes the base /etc/kubernetes/kubelet/config.json, puts the NodeConfig kubelet settings in the drop-in /etc/kubernetes/kubelet/config.json.d/40-nodeadm.conf, and runs the kubelet with --config-dir on that directory. kubeletConfigDir mounts it read-only and the hot-pod check merges its *.conf files as the kubelet does (lexical order, JSON merge patch):

helm install ergon-shared-cpus oci://ghcr.io/mimran1980/charts/ergon-shared-cpus \
  --version 0.1.6 \
  --namespace ergon-system --create-namespace \
  --set-string config.sharedCpus=0 \
  --set 'config.namespaces={trading}' \
  --set hostContract.kubeletConfig.enabled=true \
  --set hostContract.kubeletConfig.path=/etc/kubernetes/kubelet/config.json \
  --set hostContract.kubeletConfigDir.enabled=true \
  --set hostContract.sys.enabled=true \
  --set hostContract.proc.enabled=true

Without kubeletConfigDir every hot pod is refused on AL2023. The drop-in directory exists only when NodeConfig sets spec.kubelet.config; without it the plugin pod does not start.

A refused hot pod gets one line naming each failed node check in the order to fix them, with what was seen, what is needed and the fix. To check a node without a pod, run ergon-cpus explain in the plugin pod: it prints PASS, FAIL or SKIP per check and exits 1 on a failure. config.hotContract.mode: warn logs a failed check and lets the create go on while a fleet is brought into line; enforce is the default.

No node label? Set nodeSelector.ergon\.io/shared-cpus=null and the new label (for example nodeSelector.eks\.amazonaws\.com/nodegroup=trading): Helm merges maps, so the default key stays unless it is set to null.

Check the pulled image. This prints the index digest sha256:2b384eded978bf638bc5da981fda0538ef24edffb35229889e284e5bd1bbff91:

docker buildx imagetools inspect ghcr.io/mimran1980/ergon-shared-cpus:0.1.6

Chart digest sha256:407602c1216952c71076c21cac4becd69c0f43841c9b0591815a6f428514bc8d. image.digest renders repository@digest; an empty digest keeps repository:tag, and the default tag is the chart’s appVersion (0.1.6).

The chart renders every field config.File accepts, with seccomp.ioUring and ptp quoted "off". The plugin leaves them off. A later edit of the ConfigMap can turn a key on, and the pod still has to opt in. Aeron’s C media driver does not use io_uring.

admission.create defaults to false and renders a ConfigMap whose data.owner is external. Set it true to install the two named admission files (the policy, its binding, and the ergon-hot and ergon-helper PriorityClasses). A ConfigMap edit does not roll the DaemonSet. Drain first, then set layoutRevision.

helm install prints NOTES that say the chart is not published. It is published; ignore that line.

  1. Apply the hot-pod policy. These two files only, from k8s/nri-latency-pods/admission/:
kubectl apply -f priority-class.yaml -f validating-admission-policy.yaml

Leave examples/ and mutating-admission-policy.yaml unapplied. A pod labelled ergon.io/latency: hot is refused when it has an exec probe, a container with restartPolicy: Always, no ergon.io/shared-millicpus request, no required-plugins.noderesource.dev annotation naming ergon-shared-cpus, or no priorityClassName with a value above 100.

  1. Run a Guaranteed pod in an allowlisted namespace. Whole-number cpu, requests equal limits, ergon.io/shared-millicpus. The pod spec is under Pod. Inside it, ERGON_SHARED_CPUS is the housekeeping list, ERGON_ISOLATED_CPUS is the exclusive list, PID 1 Cpus_allowed_list is the shared CPUs only, and cpuset.cpus.effective is the union.

Flux: a HelmRepository of type oci at oci://ghcr.io/mimran1980/charts, chart ergon-shared-cpus version 0.1.6, targetNamespace: ergon-system, and the same config and hostContract values. Copy the two admission files into the Git repo Flux already applies. Do not point Flux at the whole admission/ directory: that directory also holds pods the policy is meant to refuse.

See it on kind

k8s/nri-shared-cpus/examples/try/run.sh creates a throwaway kind cluster (kindest/node:v1.35.1, static CPU manager, reservedSystemCPUs: "0,1"), installs this public chart with sharedCpus: "0" and the three hostContract flags, and applies the two admission files. A kind node shares the host kernel and has no isolcpus, so no hot pod can start there.

podexpected
unlabelled, cpu: "2", ergon.io/shared-millicpus: "250"Ready. Log: ERGON_SHARED_CPUS=0, non-empty ERGON_ISOLATED_CPUS, PID 1 Cpus_allowed_list of 0, nproc=1
the same, labelled ergon.io/latency: hotadmitted, then refused by the plugin: exclusive CPU not isolated
the hot pod with an exec liveness probedenied by the admission policy

The script deletes the cluster on the way out and uses a kubeconfig under /tmp.

That run shows the shared-CPU grant and the HFT admission check. It does not measure latency. Kind on Docker Desktop has no hugepage pool, no NIC PHC and no cpuset.cpus.exclusive partition to demonstrate, and this sample does not ask for those grants.

Run end to end on kind against the published chart 0.1.6 (2026-12-01).

The 21-step test/e2e.sh is a different run. It builds ergon-shared-cpus:dev from this tree. It does not pull the public chart.

What it gives

itemvalue
exclusive CPUsthe kubelet’s static CPU manager, cpu: N
shared CPUsergon.io/shared-millicpus: M adds ceil(M/1000) shared CPUs. With ergon.io/shared-burst-cpus: B it adds B shared CPUs (at least ceil(M/1000)) and the node still reserves M
start affinitythe hook pins threads that exist at create onto the shared CPUs. A later thread inherits its creator’s mask. A helper created by a pinned hot thread inherits the hot mask. The application can change affinity. A C pthread_create did that on linuxkit with no isolcpus. A Go 1.27 OS thread started from the hot thread stayed on the shared CPU. Aeron: aeron-client, created by a thread before it pinned, kept that thread’s mask (a placement test in Docker, without the plugin’s hook); under the hook on a node, not run. JVM not run
timer slack1 ns on every thread, inherited by every thread and child the program makes
pinningthe app pins hot threads by index into ERGON_ISOLATED_CPUS

M is millicpus because extended resources are whole numbers and requests must equal limits. 250 is a quarter core of scheduler accounting only: the plugin still adds one whole shared CPU, and there is no hard cap. A pod asking 100 on a node with two shared CPUs gets one of them; 1,001 to 2,000 gets both. Pods given the same shared CPU split it by their cgroups’ cpu.weight (from the cpu request), not by M: two pods measured 0.33 : 0.66 on one shared CPU (fractional shared CPUs).

To reserve little and spread wide, add ergon.io/shared-burst-cpus: B beside M (for example 50 and 2: the node reserves 50 millicpus, the cpuset spans 2 shared CPUs). It is a carrier for the number, because Kubernetes forces request equal to limit on an extended resource. The plugin sets no quota and no weight: the kernel gives the idle time. A burst below ceil(M/1000), above the node’s shared CPUs, or with no M is refused at create, and the message names the fix. The node advertises 256 burst IDs for each shared CPU and a pod uses B of them, so pods that burst fit as long as their total B stays within 256 x shared CPUs; past that a pod is Pending, never refused.

Animation, in words: an illustrative 8-CPU node has CPU 0 for NIC interrupts, CPUs 1 and 2 as the shared CPUs, and CPUs 3 to 7 in the static CPU manager’s pool; the millicpu values are illustrative and the selection follows internal/assign/assign.go. Pod A (cpu: 2, 250 m) gets exclusive CPUs 3 and 4 from the kubelet. Need(250) is 1; Choose finds no remembered set, sorts the shared CPUs by load (both 0, ties to the lower number) and picks CPU 1; Hold books 250 m there. The cgroup gets 1,3-4, the env lists the two sets apart. Pod B (cpu: 2, 1,500 m) gets 5 and 6; Need(1500) is 2, so it takes both shared CPUs and Split books 750 m on each: CPU 1 reads 1,000 m, which is accounting, not a cap. Before A’s program starts, the hook sets 1 ns timer slack on the container’s init and pins it to CPU 1; the app’s later threads copy both, and the hot thread pins itself to index 0 of ERGON_ISOLATED_CPUS, CPU 3. A’s container stops: Release drops its 250 m and keeps its remembered set. Pod C (cpu: 1, 250 m) breaks the 750 m tie to CPU 1. A restarts with a new container ID and the same key, and Choose returns the remembered CPU 1 without sorting, although CPU 2 is lighter. Deleting pod A calls ForgetPod, which clears the remembered set; otherwise only a plugin restart does, since Synchronize rebuilds the table from live containers. A side panel shows the two timer-slack settings below. Operation counts come from the code; they are not timings.

Timer slack

The kernel’s default timer slack is 50,000 ns. It is added to every sleep and to every epoll/io_uring timeout. The hook sets 1 ns, the kernel’s floor, on every thread the container has when it starts; the kernel copies it to every thread and child after that. A container that cannot have it does not start. The OCI hook runs as root, so it can write /proc/<tid>/timerslack_ns; a program can always set its own slack with prctl(PR_SET_TIMERSLACK).

The 1 ns slack takes the kernel’s 50 µs default off every sleep; its measured effect is not recorded here. The loop spins and never sleeps; the slack applies to sleeping helpers such as Aeron’s conductor. A thread a pod starts with kubectl exec has the kernel’s 50 µs, not the hook’s 1 ns.

Node setup

Do this before installing the plugin. Everything here is per node. The rest of the node checklist is Latency Pods: node setup.

settingvalue
Kubernetes>= 1.33: no CPU quota on exclusive containers (the labs ran 1.36)
kubeletcpuManagerPolicy: static; x86 full-pcpus-only; reservedSystemCPUs = the IRQ CPU(s) + the shared CPUs; cpuCFSQuota not false; feature gate DisableCPUQuotaWithExclusiveCPUs not false
kubelet config file/var/lib/kubelet/config.yaml (kubeadm, kind). The plugin pod does not start without it. Another path: --set hostContract.kubeletConfig.path=<file>. A kubelet run with --config-dir also needs hostContract.kubeletConfigDir; EKS AL2023: Use the public chart
kernel>= 6.2, cgroup v2. Boot line: isolcpus=managed_irq,domain, nohz_full and rcu_nocbs on every CPU outside reservedSystemCPUs, never on the shared ones. A cpu-partition opt-in also needs cpuset.cpus.exclusive: Linux 6.7, or a vendor kernel that backported that file. The plugin reads the file, not the version
NIC IRQsevery hardware NIC IRQ, requested and effective affinity, on the IRQ CPU(s): reservedSystemCPUs minus sharedCpus
isolated-CPU noiseTHP never and the fair server’s runtime 0 on each isolated CPU, at every boot (below). The plugin does not check them
containerd>= 2.2, NRI on, default validator on
node labelergon.io/shared-cpus=true

A pod labelled ergon.io/latency: hot is checked against the kubelet, kernel and NIC IRQ rows at every create: its exclusive CPUs must be in /sys/devices/system/cpu/isolated, the shared CPUs online and outside isolated and nohz_full. A miss refuses that create (CreateContainerError, naming the rule). Unlabelled pods get the same grants without the check.

CPU split. Pick three CPU sets on the node and write them down; every later step names one of them.

setwhoexample (8 CPUs)
exclusivethe pod’s busy-spin loops2,3 (and 4,5 for a second pod)
sharedhelpers, kubelet, containerd, system0
IRQNIC interrupts1

Kernel boot line. Isolate the exclusive CPUs only. Never the shared one.

nohz_full=2-5 rcu_nocbs=2-5 isolcpus=managed_irq,domain,2-5

kubelet: reservedSystemCPUs: "0,1" (shared + IRQ) with the policy above. Restart kubelet and check it took.

containerd: NRI on (disable = false) and the default validator on. The validator is what makes an unmet required-plugins annotation fail the create instead of starting the pod half-granted. Leave required_plugins empty: a node-wide list would also block kube-system pods and the plugin’s own pod while it is down. Leave tolerate_missing_plugins_annotation unset: a pod that carries the annotation it names skips the check, and the admission policy does not know that name.

Quiet isolated CPUs

The lab’s kernel trace named two sources of work sent to an isolated CPU that the boot line leaves on (what reached it, and the fix):

settingvaluewhynote
/sys/kernel/mm/transparent_hugepage/enablednever (madvise still runs khugepaged)khugepaged calls lru_add_drain_all: a kworker on every CPU with queued pagesor transparent_hugepage=never on the boot line
/sys/kernel/debug/sched/fair_server/cpu<N>/runtime, each isolated N0the fair server’s 1 s timer: a nohz kick and a reschedule IPI, and the tick kept onkernel 6.12+; debugfs, so lost at reboot: a oneshot unit after sys-kernel-debug.mount; safe only where nothing real-time runs on those CPUs

Apply both at every boot from a oneshot unit, and check them read-only after it runs.

Keep node events out of trading hours. Anything that calls lru_add_drain_all (block-device ioctls, systemctl daemon-reload and generators, mlock, page migration) or loads a BPF program (systemd units, a container start with seccomp, an SSH login) still reaches every isolated CPU. A systemd daily timer did both in the lab: a 40.60 µs max and one involuntary switch.

sourcerule
systemd daily timersmove them out of trading hours (systemctl list-timers)
pod churnno pod starts or restarts on the node during trading
loginsno SSH logins to the node during trading

Check the node with ergon-tune

ergon-tune reads the host and changes nothing. Every finding names what is wrong and the fix. Run it on the node, with the exclusive CPUs of the pods, the data NIC and the instance family:

ergon-tune --hot <exclusive CPUs> --nic <data NIC> --family <c7i|c7a|c8g|c9g> --tcp

Or from a pod that mounts the node’s root at /host:

ergon-tune --root /host --hot <exclusive CPUs> --require

The plugin and ergon-tune are two halves of one job: ergon-tune checks the node and the pod (isolated CPUs, CPU quotas, SMT, NIC interrupts, clocks), the plugin hands out the CPUs and refuses a hot pod that breaks the node contract.

The order to work in, on one node:

  1. Node settings: the table above.
  2. ergon-tune on the node; fix every finding.
  3. Install the chart (Use the public chart).
  4. ergon-cpus explain in the plugin pod: every failed hot-node check with its fix.
  5. The app’s start-up check: ERGON_HOST_CHECKS=require (the switch) refuses to start on a node that fails.

Step 4, in the plugin pod on that node:

kubectl -n ergon-system exec pod/<plugin pod> -- /ergon-cpus explain \
  --config /etc/ergon-shared-cpus/config.yaml \
  --kubelet-config /host/kubelet-config --host-sys /host/sys --host-proc /host/proc

On EKS AL2023 the kubelet settings sit in a drop-in directory, so add --kubelet-config-dir /host/kubelet-config-dir (the chart mounts it when hostContract.kubeletConfigDir.enabled is set), or explain reports different kubelet settings from the ones the plugin reads.

Install on Kubernetes

The plugin is public. No image pull secret.

whataddress
imageghcr.io/mimran1980/ergon-shared-cpus:0.1.6 (and :latest)
digest of 0.1.6 and latestsha256:2b384eded978bf638bc5da981fda0538ef24edffb35229889e284e5bd1bbff91
chartoci://ghcr.io/mimran1980/charts/ergon-shared-cpus version 0.1.6
helm install ergon-shared-cpus oci://ghcr.io/mimran1980/charts/ergon-shared-cpus \
  --version 0.1.6 \
  --namespace ergon-system --create-namespace \
  --set-string config.sharedCpus=0 \
  --set 'config.namespaces={trading}' \
  --set hostContract.kubeletConfig.enabled=true \
  --set hostContract.sys.enabled=true \
  --set hostContract.proc.enabled=true

config.sharedCpus is this node’s shared CPU. For the 8-CPU split above that is 0: inside reservedSystemCPUs, and not the IRQ CPU. The chart creates ergon-system with the privileged Pod Security labels and selects nodes labelled ergon.io/shared-cpus=true. It does not label nodes, and it does not set the boot line, the kubelet, or containerd.

Do the node setup above first, then the steps below. The public install is Use the public chart. Step 4 below is the local image ergon-shared-cpus:dev. The kind sample that pulls the public chart is See it on kind.

1. Label the nodes that take the plugin

kubectl label node <node> ergon.io/shared-cpus=true

Only labelled nodes run the DaemonSet. A pod that asks for the device on an unlabelled node stays pending.

2. Edit deploy/configmap.yaml

This is the step people get wrong. The file is k8s/nri-shared-cpus/deploy/configmap.yaml, and it becomes /etc/ergon-shared-cpus/config.yaml in the plugin’s container.

sharedCpus: "0"          # the node's shared CPUs, kernel cpulist
oversubscription: 1
namespaces: ["trading"]  # who may opt in. Empty refuses every pod
defaultAffinity: shared
annotationOptIn: false
devRoot: /host/dev       # where the DaemonSet mounts the host's /dev; without
                         # it the plugin finds no PHC and refuses ptp grants

# These three are "off" by default. A latency node turns the first two on.
# Each one is a node-level permission: the pod still opts in by annotation,
# and a pod that asks for a grant this field does not allow is refused.
seccomp:
  ioUring: "allow"       # default "off". Without it, a pod asking for
                         # seccomp.ergon.io/<ctr>: "io-uring" is refused.
                         # For apps that use io_uring. Aeron's C media
                         # driver does not use it. Needs containerd 2.3
                         # or later (earlier ones are refused)
ptp: "auto"              # default "off". Without it, a pod asking for
                         # ptp.ergon.io/<ctr> is refused. "auto" allows any
                         # PHC the node has; a /dev/ptp* path allows only that
                         # one. The grant is read-only, root included,
                         # and needs containerd 2.2 or later

Rules:

  • sharedCpus must sit inside the kubelet’s reservedSystemCPUs, minus the IRQ CPU(s). In the table above that is 0.
  • namespaces is an allowlist. Create those namespaces before applying.
  • Quote off, on, yes, no. YAML 1.1 turns unquoted ones into booleans.
  • An unknown field or an out-of-range value stops the plugin at start, and the message names the field.
  • off is not harmless. It is a refusal. A pod whose annotation asks for a grant the ConfigMap does not allow does not start: the kubelet shows CreateContainerError and the text names the field to change.

3. Install the public chart

Use the helm install at the top of this section. One Helm release per shared-CPU layout: the chart has one ConfigMap.

The plugin is root on the node and installs an executable at /opt/ergon/bin/ergon-cpus. Only this repository’s publish workflow pushes.

Kind, or a node with no registry: docker build -t ergon-shared-cpus:dev . from k8s/nri-shared-cpus, load that image, and apply the three manifests in the next step. deploy/daemonset.yaml ships image: ergon-shared-cpus:dev with imagePullPolicy: IfNotPresent.

4. Apply the three manifests

Skip this when the Helm release above is installed. It is the kind path.

kubectl apply -f deploy/namespace.yaml \
              -f deploy/configmap.yaml \
              -f deploy/daemonset.yaml

The :dev DaemonSet needs eight host paths: /var/run/nri, /var/lib/kubelet/device-plugins and /opt/ergon/bin read-write, plus /dev at /host/dev, the host cgroup v2 tree at /sys/fs/cgroup, /var/lib/kubelet/config.yaml at /host/kubelet-config, /sys at /host/sys and /proc at /host/proc, the last five read-only. The kubelet file is a File mount: the pod does not start when that path is missing. The namespace is labelled Pod Security privileged for that reason. The plugin is root on the node: anything on the NRI socket can change any container.

5. Verify the plugin before any workload

The pod is Ready on every labelled node, allocatable shows ergon.io/shared-millicpus greater than zero, /readyz is healthy, and the logs show no config error (strict YAML: a bad field stops it). If allocatable is empty the device plugin did not register: check the logs and that /var/lib/kubelet/device-plugins is mounted.

6. Run a pod and check the grants landed

Use the pod under Pod. Inside it:

kubectl exec trader -- sh -c 'echo isolated=$ERGON_ISOLATED_CPUS shared=$ERGON_SHARED_CPUS'
kubectl exec trader -- cat /proc/1/status | grep Cpus_allowed_list

Cpus_allowed_list must print the shared CPUs only. That is the point of the plugin.

Config

/etc/ergon-shared-cpus/config.yaml, from the ConfigMap. Strict YAML: an unknown field is an error at start. No hot reload. A ConfigMap edit does not roll the DaemonSet. Drain trading workloads, then set layoutRevision (or restart the pods), before a new CPU layout is used. Running grants stay as they were at create.

fielddefaultwhat it is
sharedCpusrequiredthe housekeeping CPUs, kernel cpulist ("4" or "0,2"). Inside reservedSystemCPUs, never the IRQ CPU(s)
oversubscription11–100. Capacity is len(sharedCpus) x 1000 x this; the max is 100,000 device IDs (the kubelet’s 4 MiB gRPC limit)
namespacesemptythe allowlist. Empty refuses every opt-in. Each must be a valid namespace name
defaultAffinitysharedshared injects the hook that starts every thread on the shared CPUs. all injects nothing; use the ergon-cpus wrapper (see Bottlerocket below)
hookPath/opt/ergon/bin/ergon-cpuswhere the daemon writes the hook on the node. Must be a clean absolute path ending in /ergon-cpus; the daemon writes it as root, so the name is fixed
annotationOptInfalseallow the pod annotation cpu-shared.ergon.io/<container> as a fallback when the device plugin is not used
metricsAddress:9466serves /metrics, /healthz and /readyz
rlimits.memlock, .nofile, .rtPrio, .niceunsetthe ceiling a pod may ask for by kind. "inf" or a positive count. The pod asks for kinds, never values
seccomp.ioUring (nested: seccomp: then ioUring:)offallow widens the container’s seccomp profile for io_uring_*. See Latency Pods
seccompProfilePath/etc/ergon-shared-cpus/ergon-io-uring.jsonthe shipped io_uring profile on the node, the fallback for a pod that cannot take the NRI grant
devRoot/devwhere this process sees the host’s /dev. The DaemonSet mounts it read-only at /host/dev so the plugin can stat the PHC and PM QoS nodes; granted paths stay /dev/...
ptpoffoff, auto, or a /dev/ptp* path the node has. auto grants the NIC’s PHC
hugepagesAeronDirunsetabsolute AERON_DIR to export when the pod mounts a sized hugetlbfs

cgroupRoot is not a field. The parser rejects it. The binary uses /sys/fs/cgroup, and the DaemonSet mounts the host cgroup tree read-only at that path. The createRuntime hook matches the same path against /proc/<pid>/cgroup.

The chart can also write profiles and nodeProfileLabel instead of the flat fields. At startup the binary reads its node once and uses the label’s value as the profile name. A missing or unknown label stops the process. It does not watch the node and it does not change the label. Setting sharedCpus and profiles in the same file is rejected. Drain before changing a label or a profile. Containers that are already running keep the helper CPUs recorded at create. This selection was not run on a multi-node cluster.

Quote off, on, yes and no in this file. YAML 1.1 turns unquoted ones into booleans.

Unknown fields and out-of-range values are refused at start, each naming its field: oversubscription outside 1–100, a namespaces entry that is not a namespace name, hookPath not ending in /ergon-cpus, an rlimits value that is neither inf nor a positive count, ptp / seccomp.ioUring outside their sets. A schedFifo key from an older release is refused the same way.

Pod

apiVersion: v1
kind: Pod
metadata:
  name: trader
  namespace: trading                       # must be in the plugin's allowlist
  annotations:
    required-plugins.noderesource.dev: '["ergon-shared-cpus"]'
spec:
  nodeSelector: { ergon.io/shared-cpus: "true" }
  containers:
  - name: app
    image: my-app
    resources:
      requests: { cpu: "2", memory: 1Gi, ergon.io/shared-millicpus: "250" }
      limits:   { cpu: "2", memory: 1Gi, ergon.io/shared-millicpus: "250" }

Inside the container:

itemvalue
cpuset.cpus.effectivethe exclusive CPUs plus the shared ones
affinity of PID 1 and of every new threadthe shared CPUs only
nproc, GOMAXPROCS, availableProcessors()usually the shared CPUs: they count the affinity mask

Env vars

namevalueformat
ERGON_ISOLATED_CPUSthe exclusive CPUssorted comma list, no ranges: 1,5
ERGON_SHARED_CPUSthis container’s shared CPUssame
ERGON_ISOLATED_CORESthe exclusive CPUs by physical coregroups by ;, CPUs by ,: 1,5;2,6
ERGON_SHARED_MILLICPUSMdecimal
ERGON_SHARED_BURST_CPUSB, only when the pod asked for a burstdecimal, CPUs
ERGON_HELPER_CPUSsame as ERGON_SHARED_CPUScomma list
OPENSHIFT_ISOLATED_CPUSsame as ERGON_ISOLATED_CPUSkernel cpulist with ranges
OPENSHIFT_SHARED_CPUSsame as ERGON_SHARED_CPUSsame

Read the CPUs from these variables or from cpuset.cpus.effective, never from the process’s own affinity: the start mask is the shared CPUs.

Pinning by index

Pin each hot thread to isolated index i. The app never needs the real CPU numbers.

/* SPDX-License-Identifier: Apache-2.0 */
/*
 * Pin a hot thread by index into ERGON_ISOLATED_CPUS. Leave helpers alone:
 * every thread already starts on the shared CPUs.
 *
 * Build:  cc -O2 -o pin pin.c
 * Run:    in a container that asked for ergon.io/shared-millicpus.
 */
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* The i-th number of a list like "1,5"; -1 if there is none. */
static int nth_cpu(const char *list, int i)
{
    if (list == NULL)
        return -1;
    for (const char *p = list; *p != '\0'; i--) {
        char *end;
        long cpu = strtol(p, &end, 10);
        if (end == p)
            return -1;
        if (i == 0)
            return (int)cpu;
        p = (*end == ',') ? end + 1 : "";
    }
    return -1;
}

/* Pin the calling thread to isolated CPU index i. Returns the CPU, or -1. */
int pin_isolated(int i)
{
    int cpu = nth_cpu(getenv("ERGON_ISOLATED_CPUS"), i);
    if (cpu < 0)
        return -1;
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    return sched_setaffinity(0, sizeof set, &set) == 0 ? cpu : -1;
}

/* Report which CPU the calling thread is on and where its mask is. */
static void report(const char *who)
{
    int now = sched_getcpu();
    cpu_set_t set;
    CPU_ZERO(&set);
    if (sched_getaffinity(0, sizeof set, &set) != 0) {
        perror("sched_getaffinity");
        return;
    }
    printf("%s: running on cpu %d, mask", who, now);
    for (int c = 0; c < CPU_SETSIZE; c++)
        if (CPU_ISSET(c, &set))
            printf(" %d", c);
    printf("\n");
}

int main(void)
{
    const char *iso = getenv("ERGON_ISOLATED_CPUS");
    const char *sh = getenv("ERGON_SHARED_CPUS");
    printf("ERGON_ISOLATED_CPUS=%s\nERGON_SHARED_CPUS=%s\n",
           iso ? iso : "(unset)", sh ? sh : "(unset)");

    /* Every thread starts on the shared CPUs. */
    report("helper (default)");

    /* Pin the hot thread to isolated index 0. */
    int cpu = pin_isolated(0);
    if (cpu < 0) {
        fprintf(stderr, "pin_isolated(0) failed\n");
        return 1;
    }
    printf("pinned the hot thread to isolated index 0 = cpu %d\n", cpu);
    report("hot (pinned)");

    /* Index 1, when the pod asked for more than one CPU. */
    int cpu1 = pin_isolated(1);
    if (cpu1 >= 0) {
        printf("isolated index 1 = cpu %d\n", cpu1);
        report("hot2 (pinned)");
    }
    return 0;
}

In Rust the ergo-cpus crate (cpus/, not released yet) reads these variables, pins by index, and has an AffinityGuard that puts a pinned hot thread on the shared CPUs while it creates helpers. It needs no unsafe.

Rules:

  • leave helpers alone: they start on the shared CPUs;
  • create helpers from a thread that is still on the shared set (a new thread copies its creator’s mask);
  • each sleepy helper checks sched_getcpu() when it wakes and alarms if it is not on ERGON_SHARED_CPUS;
  • never a spinner or SQPOLL on a shared CPU. Give SQPOLL a CPU of the pod’s own outside ERGON_HELPER_CPUS, and refuse to start when there is none;
  • two indices are two physical cores only when they are two groups in ERGON_ISOLATED_CORES. On SMT, 1,5 is one core and its two threads share every execution unit: two “hot cores” there is one hot core.

A core is never split between the exclusive and the shared CPUs. On SMT the hot thread and the helpers would time-share one physical core, which is the contention this whole setup exists to remove. The plugin refuses such a container rather than start it claiming an isolation it does not have. On x86 keep SMT off, or use full-pcpus-only and put whole cores in reservedSystemCPUs and in sharedCpus. On an SMT node the node contract checks this up front: smt-whole-cores (the shared and reserved CPUs are whole cores) and smt-full-pcpus-only (the kubelet runs static with full-pcpus-only) fail a hot pod with the value seen, the value needed and the fix. Without SMT both rows are skipped. The rows read what the kubelet runs with: the kubelet process’s own argv from the host proc (flags such as --cpu-manager-policy-options and --reserved-cpus override the file; every kubelet process found is checked, and one with the option off fails the row), the /configz copy when mounted (a static copy: when it disagrees with the live argv the row fails and says to refresh it), and the kubelet file and its drop-ins. When no kubelet process is found and no configz is mounted, ergon-cpus explain says that flag overrides are unverifiable and which chart value enables each source.

Worked example: an Aeron media driver

Two pinned cores (sender and receiver) plus the conductor on the shared CPU, with huge pages. This is the layout a latency node wants.

Node boot line (from the table above), for exclusive CPUs 2 and 3, shared 0, IRQ 1:

nohz_full=2-3 rcu_nocbs=2-3 isolcpus=managed_irq,domain,2-3 hugepagesz=2M hugepages=512

ConfigMap (sharedCpus: "0"), kubelet (reservedSystemCPUs: "0,1"), and a namespace in the allowlist.

Pod. Three grants on top of the shared CPU: a sized hugetlbfs for AERON_DIR, io_uring seccomp, and the NIC PHC. The isolation of CPUs 2-3 comes from the boot line, not from a grant: cpu-partition needs the program to move its own threads between cgroups (Latency Pods), and the media driver does not.

apiVersion: v1
kind: Pod
metadata:
  name: aeron-driver
  namespace: trading
  labels: { ergon.io/latency: "hot" }
  annotations:
    required-plugins.noderesource.dev: '["ergon-shared-cpus"]'
    hugepages.ergon.io/app: "2M"          # sized hugetlbfs for AERON_DIR
    seccomp.ergon.io/app: "io-uring"      # for apps that use io_uring; Aeron does not
    ptp.ergon.io/app: "auto"              # the NIC's PHC
spec:
  nodeSelector: { ergon.io/shared-cpus: "true" }
  priorityClassName: ergon-hot              # k8s/nri-latency-pods/admission/priority-class.yaml
  containers:
  - name: app
    image: ergon-media-driver:dev
    command: ["ergon-cpus",
              "--env", "AERON_SENDER_CPU_AFFINITY=isolated:0",
              "--env", "AERON_RECEIVER_CPU_AFFINITY=isolated:1",
              "--", "media_driver"]       # rusteron-media-driver's binary
    env:
    - { name: AERON_THREADING_MODE, value: DEDICATED }
    - { name: AERON_DIR, value: /dev/hugepages/aeron }   # set by the app, see below
    resources:
      requests: { cpu: "2", memory: 2Gi, ergon.io/shared-millicpus: "250", hugepages-2Mi: 256Mi }
      limits:   { cpu: "2", memory: 2Gi, ergon.io/shared-millicpus: "250", hugepages-2Mi: 256Mi }

What each piece does:

pieceeffect
cpu: "2"two exclusive CPUs from the static CPU manager: the sender’s and the receiver’s
ergon.io/shared-millicpus: "250"the plugin adds the shared CPU and starts every thread there
AERON_SENDER_CPU_AFFINITY=isolated:0sender on the pod’s first exclusive CPU
AERON_RECEIVER_CPU_AFFINITY=isolated:1receiver on its second
media_driverthe C media driver, as built by rusteron-media-driver (cargo install rusteron-media-driver --features static); it reads the same AERON_* variables as Aeron’s aeronmd, which works here too
AERON_CONDUCTOR_CPU_AFFINITY unsetthe conductor stays on the shared CPU
AERON_THREADING_MODE=DEDICATEDsender, receiver and conductor on their own threads
hugepages.ergon.io/app: "2M" + hugepages-2Mia sized hugetlbfs mounted at /dev/hugepages
AERON_DIR on that hugetlbfsthe CnC file and the terms are 2 MiB pages, not 4 KiB
seccomp.ergon.io/app: "io-uring"the profile gains the io_uring_* calls an app that uses io_uring needs; never Unconfined
ptp.ergon.io/app: "auto"the NIC’s PHC, for clock work
ergon.io/latency: "hot" (pod label)the admission policy refuses exec probes and restartPolicy: Always sidecars
isolcpus=managed_irq,domain,2-3 on the boot lineCPUs 2-3 leave the scheduler’s load-balancing domains (settings)

The app sets AERON_DIR itself. The plugin exports ERGON_HUGEPAGES_DIR, ERGON_HUGEPAGE_SIZE, AERON_FILE_PAGE_SIZE=2097152 and AERON_TERM_BUFFER_SPARSE_FILE=false. It does not set AERON_DIR, because the app must create the subdirectory:

mkdir -p "$ERGON_HUGEPAGES_DIR/aeron"
export AERON_DIR="$ERGON_HUGEPAGES_DIR/aeron"

An unsized hugetlbfs (what emptyDir: {medium: HugePages} gives you) is rejected by Aeron. That is why the size comes from the annotation.

Affinity variables:

variableagenthere
AERON_SENDER_CPU_AFFINITYsenderisolated:0
AERON_RECEIVER_CPU_AFFINITYreceiverisolated:1
AERON_CONDUCTOR_CPU_AFFINITYconductorleave unset: it starts on the shared CPUs
AERON_DRIVER_NATIVE_RESOURCE_AGENT_CPU_AFFINITYnative resource agentleave unset
AERON_THREAD_AFFINITY_USE_CPUSET_OFFSETS (before Aeron 1.54: AERON_DRIVER_CPUSET_AFFINITY)makes the four above offsets into the cgroup cpusetkeep false; the wrapper refuses to translate when either is true

isolated:0 is an index, not a CPU number. cpu: "2" gives the pod two exclusive CPUs; the static CPU manager picks which (here 2 and 3, on another node maybe 5 and 9) and the plugin lists them, sorted, in ERGON_ISOLATED_CPUS. isolated:<i> is position i in that list, counted from 0, so the manifest stays the same on every node:

ERGON_ISOLATED_CPUSisolated:0isolated:1isolated:2
2,3CPU 2CPU 3refused: the pod has 2
5,9CPU 5CPU 9refused

ergon-cpus turns each spec into the real CPU number and sets the variable to it (AERON_SENDER_CPU_AFFINITY=2) before exec, so the driver sees a plain number and needs no offset mode. An index past the list is an error, not a wrap. It also sets its own affinity to the shared CPUs, so the driver starts there.

Check it worked:

kubectl exec aeron-driver -- sh -c 'echo isolated=$ERGON_ISOLATED_CPUS shared=$ERGON_SHARED_CPUS'
kubectl exec aeron-driver -- sh -c 'echo hugepages=$ERGON_HUGEPAGES_DIR size=$ERGON_HUGEPAGE_SIZE'
kubectl exec aeron-driver -- sh -c 'ps -L -o pid,tid,psr,comm | head'

psr must show the sender and receiver on 2 and 3 and every other thread on 0. mount | grep hugepages must show a size, not just hugetlbfs.

Fractional shared CPUs

  • Extended resources are whole numbers and requests must equal limits, so the unit is millicpus: 250 = a quarter.
  • The plugin adds ceil(M/1000) shared CPUs, at least one. It does not grant the whole helper set unless M = 1000 × |S|. With oversubscription: 1 that request takes every configured helper CPU, using the same allocator.
  • A reconnect keeps the helper CPUs recorded at create. It does not pick replacements for a container that is already running.
  • The fraction is scheduler accounting only. With 2 shared CPUs and oversubscription 2, a node offers 4000; sixteen pods at 250 fit.
  • There is no hard cap. Helpers may use the whole shared CPU, shared with the kubelet, containerd, system daemons and other pods.
  • Measured on two shared CPUs, busy helpers: 100 millicpus got one shared CPU and used 0.99 cores of it, 1,001 got both and used 1.99, idle helpers 0.04; nr_throttled 0. Two pods on one shared CPU (cpu: 1 and cpu: 2, 100 millicpus each) split it 0.33 : 0.66, by cgroup cpu.weight from the integer cpu request, not by millicpus (scaling).
  • A helper wake-up on a shared CPU waits on the node’s other load; the size of that wait is not measured. It slows connects and the conductor, not the loop.

Fail closed

eventeffectguard
plugin down at createNRI makes no changerequired-plugins.noderesource.dev makes the create fail; the wrapper refuses without ERGON_SHARED_CPUS; the resource does not allocate
kubelet restart, plugin upthe re-write keeps the unionthe plugin re-widens in UpdateContainer
kubelet restart, plugin downcpuset shrinks to the exclusive CPUs; helpers fall onto them until the plugin is backnothing prevents it. The pod detects it and leaves Ready (below); Synchronize re-widens on reconnect
sharedCpus outside reservedSystemCPUsevery shared-CPU opt-in is refused, hot or notthe kubelet config, when mounted. hotContract.mode: warn lets it go on
a node check overruns the NRI request timeoutthe create is refused (warned in warn mode)the plugin cuts the check off in time
host drifta new hot create is refusedthe plugin stays connected. /healthz stays up. This is not a liveness restart
hook binary missingthe create failsthe DaemonSet installs the binary before it connects

Running pods during a plugin outage

required-plugins protects creation, not a pod that is already running. While the plugin is down, a kubelet restart rewrites the cpuset to the exclusive CPUs only. Every helper thread moves onto them and competes with the loop until the plugin reconnects.

The contract:

  • Detection is in the pod. Placement holds while cpuset.cpus.effective contains ERGON_ISOLATED_CPUS and ERGON_SHARED_CPUS. In a cpu-partition pod the partition holds the exclusive CPUs, and the probe also requires the ergon-isolated child’s cpuset.cpus.partition to read isolated, not isolated invalid. During the outage nothing on the node is running to report a shrunk cpuset.
  • Pod spec. Start the app as ergon-cpus --ready-addr :8086 -- <app> and add an httpGet readiness probe on :8086/placement (periodSeconds: 1, failureThreshold: 1). The admission policy denies exec probes on hot pods; an httpGet probe runs from the kubelet. The endpoint answers 503 placement broken: <reason> while a list is missing or the partition is invalid, and 200 placement verified otherwise. The endpoint listens on every interface (the kubelet probes the pod IP) and returns the CPU lists; on a hostNetwork pod choose a port that is free on the node.
  • App. While the endpoint answers 503, stop the work that needs the exclusive CPUs. A helper thread can poll it on localhost or make the same comparison itself; the hot thread never does.
  • Node. On reconnect the plugin’s Synchronize re-widens every managed container and counts it in ergon_shared_cpus_rewidened_total{event="sync"}. The counter belongs to the plugin process, starts at 0 and goes up only when a container had lost its shared CPUs. Alert on ergon_shared_cpus_rewidened_total{event="sync"} > 0 (or on the plugin’s sync: re-widen log line), not on increase(): the re-widen comes right after a new plugin pod connects, usually before its first scrape, and increase() ignores a new series’ first sample. The alert keeps firing until that plugin pod restarts. The pod is Ready again only once its cpuset holds both lists. In the e2e the helper was back on its shared CPU by then. test/e2e.sh steps 9, 10 and 18 check this on kind and time it (plugin outage timings).

Limits and what is not verified

  • The plugin is root on the node. With the install flags the chart mounts eight host paths: /var/run/nri, /var/lib/kubelet/device-plugins and /opt/ergon/bin read-write; the host’s /dev at /host/dev, /sys/fs/cgroup, the kubelet config, /sys and /proc read-only. The :dev manifest mounts the same. No hostPID, no hostNetwork, not privileged, capabilities.drop: [ALL], readOnlyRootFilesystem: true, seccomp RuntimeDefault. API access only to create Events (chart events.enabled, default on; off removes --events and the RBAC, and the token too unless config.profiles needs it), plus a get-only ClusterRole on nodes when config.profiles is set. Only namespaces in the allowlist may opt in.
  • AKS has no supported way to enable containerd NRI plugins and no reservedSystemCPUs. Not supported.
  • CRI-O users use its shared_cpuset instead.
  • Bottlerocket: whether runc may exec a hook binary that a pod wrote to a host path is not verified. Use defaultAffinity: all and the wrapper until checked.
  • kubectl exec and exec probes start on any CPU of the cpuset, exclusive ones included. No exec probes on hot containers; run debug commands as ergon-cpus -- <cmd>.
  • In-place CPU resize leaves the CPU env stale. Use resizePolicy: RestartContainer for cpu.
  • EKS AL2023: the kubelet settings are in a config.json.d/ drop-in, so hot pods need kubeletConfigDir (Use the public chart). Without it every hot pod is refused there; unlabelled pods get the grants.
  • The plugin cannot see the kubelet’s command line. A kubeletConfigDir the kubelet does not read (no --config-dir) makes the check trust drop-ins the kubelet ignores; kubeletConfigZ with a fresh /configz copy cross-checks.
  • Measured on one Azure Cobalt VM: the exclusive core with the plugin on, helpers on the shared CPU and the quiet-CPU settings: p50 0.02 µs, p99.99 0.03 µs, max 4.81 to 5.52 µs over 3 reps of 60 s, 0 involuntary switches, no interrupt on the spin’s CPU; the gaps left have no guest event (the hypervisor’s 3.5 to 5.5 µs floor) (benchmarks).
  • Verified on EKS AL2023 (runs eks-nri-20261025-070515, eks-nri-20261025-082023): the NRI socket, nodeadm TOML merge, the kubelet drop-in merge, /opt writable, system-node-critical outside kube-system. A warm ENI the VPC CNI attaches after boot came up with its IRQs on the shared CPU, and the plugin refused hot pods until they were re-pinned: pin IRQs again after the CNI attaches an ENI.
  • Not measured: how often node events reach isolated CPUs in production; the spin loop on EKS.

Decision. Use it on kind or a self-managed node where you can set reservedSystemCPUs and enable NRI. With the quiet-CPU settings the exclusive cores took no context switch and nothing above the hypervisor’s 5.5 µs in steady state; keep node events out of trading hours. Not for AKS or CRI-O.

Latency pods

Five things a normal Kubernetes pod cannot do, and what to use instead. They live in k8s/nri-latency-pods (node setup and the admission policy) and k8s/nri-shared-cpus (the NRI plugin). This page is the contract.

In short: five opt-in grants: a sized hugetlbfs for Aeron’s directory, an isolated cpuset partition, an io_uring seccomp profile, an admission policy against exec probes and sidecars, and device grants (the NIC’s PHC). Each is a mechanism; none has a measured latency effect. Real-time scheduling (SCHED_FIFO) is not built (why).

Status: the grants ship in the public image ghcr.io/mimran1980/ergon-shared-cpus:0.1.6. Install it with the chart oci://ghcr.io/mimran1980/charts/ergon-shared-cpus version 0.1.6 (Shared CPUs). On EKS AL2023 a pod labelled ergon.io/latency: hot needs kubeletConfigDir, which lets the plugin read nodeadm’s kubelet drop-in; the EKS install line is on that page. This page’s admission YAML and node units are not an image. The chart writes seccomp.ioUring and ptp as "off". k8s/nri-shared-cpus/examples/try installs that chart and shows three things on kind: the shared-CPU grant on an unlabelled pod, the plugin refusing a hot pod (a kind node has no isolcpus), and this page’s admission policy denying an exec probe. just test-nri-published runs it as part of just release; it last ran on kind against chart 0.1.6. It does not exercise hugepages, the cpuset partition, io_uring seccomp, or the PHC. The five-grant kind e2e (test/e2e.sh) builds the plugin from source. On EKS the plugin’s install is verified (Shared CPUs); the grants’ latency modes have not run there. No latency figure is measured.

The five

Every grant is opt-in by pod annotation. A grant that cannot be given is refused: the kubelet shows the text in the pod’s events as CreateContainerError, and the text names the fix. A pod author names kinds and modes only; values come from the plugin config or the node’s facts.

#extensionmechanismpod opt-inenv the app sees
1sized hugetlbfs for AERON_DIRNRI AddMount type: hugetlbfs with pagesize=2M,size=N, plus AddLinuxHugepageLimit; N is the container’s hugepages-2Mi limithugepages.ergon.io/<ctr>: "2M" and a hugepages-2Mi resource (requests = limits)ERGON_HUGEPAGES_DIR, ERGON_HUGEPAGE_SIZE, AERON_FILE_PAGE_SIZE=2097152, AERON_TERM_BUFFER_SPARSE_FILE=false
2cpuset.cpus.partition=isolated on the exclusive CPUsa createRuntime hook makes a threaded child cgroup holding only those CPUs, unions them into the ancestors’ cpuset.cpus.exclusive, then writes cpuset.cpus.partition=isolated, and reads every write back. Takes a process, then single threads (see below)cpu-partition.ergon.io/<ctr>: "isolated"ERGON_ISOLATED_CGROUP, ERGON_ISOLATED_CPUS, ERGON_SHARED_CPUS
3io_uring seccomp profile(a) NRI SetLinuxSeccompPolicy: the request’s profile plus the io_uring_* allow rules; (b) fallback, pod field seccompProfile: Localhostseccomp.ergon.io/<ctr>: "io-uring" (or the Localhost fallback)ERGON_SECCOMP
4no exec probes, no always-restart sidecarsValidatingAdmissionPolicy (CEL, GA 1.30)pod label ergon.io/latency: "hot"—
5device grantsNRI AddDevice, plus a read-only bind of the node facts fileptp.ergon.io/<ctr>: "auto" (the NIC PHC); cpuqos.ergon.io/<ctr> (/dev/cpu_dma_latency, x86 only)ERGON_PTP_DEVICE, ERGON_NODE_FACTS, ERGON_CPU_DMA_LATENCY

Ride-along: rlimits.ergon.io/<ctr> grants MEMLOCK, NOFILE and RTPRIO (a limit value only, see below). The values are ceilings the pod may ask for, set in the plugin config.

Also numa.ergon.io/<ctr>: "0", "0,1" or "" binds the container’s memory to those NUMA nodes (cpuset.mems and MPOL_BIND). "" means the data NIC’s node, which needs that node recorded; on a one-node machine the only node is the answer. A request the node cannot answer is refused and says why: an unread topology, a node the machine does not have, or "" with several nodes and no NIC node. A binding is never dropped in silence.

The five grants on one pod. Everything stays inside the pod’s own cpuset: exclusive CPUs from the kubelet’s static CPU manager, shared CPUs from ergon.io/shared-millicpus. Helpers go on the shared CPUs; SQPOLL takes an exclusive CPU of the pod’s own, never a shared CPU: it spins.

flowchart TD
    POD["latency pod: exclusive CPU(s) and shared CPU(s) in its cpuset"]
    POD --> A["1 hugepages.ergon.io"]
    POD --> B["2 cpu-partition.ergon.io"]
    POD --> C["3 seccomp.ergon.io/io-uring"]
    POD --> D["4 ergon.io/latency hot"]
    POD --> E["5 ptp. and cpuqos.ergon.io"]
    A --> A1["sized hugetlbfs + hugepage limit"]
    B --> B1["child cgroup, isolated partition"]
    C --> C1["seccomp + io_uring_* rules"]
    D --> D1["no exec probes, no Always sidecars"]
    E --> E1["PHC, cpu_dma_latency, node facts"]
    SQ["helpers on shared CPUs"] -.-> POD

1. The app owns AERON_DIR

The plugin mounts a sized hugetlbfs at /dev/hugepages and exports ERGON_HUGEPAGES_DIR, ERGON_HUGEPAGE_SIZE, AERON_FILE_PAGE_SIZE=2097152 and AERON_TERM_BUFFER_SPARSE_FILE=false. It does not set AERON_DIR. The app creates $ERGON_HUGEPAGES_DIR/aeron and points AERON_DIR there.

Why: an unsized hugetlbfs is what an emptyDir medium: HugePages gives you, and Aeron refuses it. A 4 KiB AERON_DIR takes a page fault on each first touch of a page. Latency effect not measured here.

A DPDK NIC pair (dpdk.ergon.io/<ctr>: "ena-pair", off by default). It needs a NIC device plugin, not shipped here, that puts RUSTERON_DPDK_SENDER_{PCI,IPV4_CIDR,GATEWAY} in the container’s env; this opt-in copies them into the env keys listed in k8s/nri-latency-pods/README.md, among them ERGON_DPDK_PCI, ERGON_DPDK_ADDR and ERGON_DPDK_GATEWAY. An app that reads the pair itself does not need it. A missing, empty or unparsable value refuses the pod and names the key. Nothing here scans sysfs, runs dpdk-devbind, reads the node’s default route (that is the management NIC), or sets AERON_DIR.

2. Isolated partition

cpuset.cpus.partition=isolated makes the kernel treat the set as isolated: no load balancing into it (cgroup-v2). The grant is applied to a child cgroup so the pod’s own cgroup keeps its shared CPUs. Latency effect not measured here.

The child is threaded, and a threaded child is a legal partition root (k8s/nri-shared-cpus/internal/cpuset/partition.go). So:

app shapehow the exclusive CPUs are used
one process whose threads all belong on the exclusive CPUswrite the pid to $ERGON_ISOLATED_CGROUP/cgroup.procs, then pin each thread to ERGON_ISOLATED_CPUS
hot threads in a multi-threaded processwrite the pid to $ERGON_ISOLATED_CGROUP/cgroup.procs first, then move each helper thread back to the container cgroup through its cgroup.threads. The kernel confines the hot threads to the exclusive CPUs and the helpers to the shared ones (kernel lane: test/cgroup/kernel_test.go, TestOneThreadCanLiveInThePartition)

These writes need a writable cgroup mount. containerd mounts /sys/fs/cgroup read-only in an unprivileged container, so there the cgroup.procs write fails and the move has to come from the node: the pod publishes its pid and waits, and a privileged node agent moves it only if exactly one task of that container’s cgroup has that pid. The kind e2e lane moves from the node this way.

A program that does not make these moves itself, such as Aeron’s C media driver, keeps the boot line’s isolation and sched_setaffinity: see the worked example.

cpuset.cpus.exclusive is a replace, not a union, so every directory the new partition shares with an already-running pod has to be updated with the union of both reservations. The hook does that under a lock and reads every write back; a write that does not stick fails the create.

/sys/fs/cgroup (the cgroup root)
has no cpuset.cpus.exclusive: never written
kubepods.slice
⑤ cpuset.cpus.exclusive ∪= E
the pod’s slice
⑤ cpuset.cpus.exclusive ∪= E
container cgroup · cpuset E ∪ S · helper threads run here on S
② cgroup.subtree_control ← cpuset
⑤ cpuset.cpus.exclusive ∪= E (last of the ⑤ writes)
<container>/ergon-isolated · the hot thread runs here on E
① mkdir
③ cgroup.type ← threaded
④ cpuset.cpus ← E
⑥ cpuset.cpus.exclusive ← E, written outright
⑦ cpuset.cpus.partition ← isolated
⑤ writes a union: the file replaces
so each level keeps the CPUs another pod’s partition reserved there. Written outermost first, down to the container. The child is this container’s alone, so ⑥ is written outright.
The container’s process
one hot thread, some helper threads
⑧ first the whole process: a thread moves inside the threaded subtree only once its process is in there
⑨ then each helper back to the container
Result: the helpers’ affinity is S, the hot thread’s E
Who runs it: the createRuntime hook
ergon-cpus hook [--shared S] --isolated E
--partition-child P
One lock
every write runs under flock(LOCK_EX) on /run/ergon-shared-cpus.partition.lock
Read back
every CPU-list write is read back; at the end the partition must read isolated
Refused before any write
when E is empty, or E and S overlap
On failure
undo only what this call added to the ancestors; remove the child only if it made it
What the app sees
ERGON_ISOLATED_CGROUP, ERGON_ISOLATED_CPUS, ERGON_SHARED_CPUS
E = the container’s exclusive CPUs, S = its shared CPUs (e.g. E = {3}, S = {1}; illustrative). ①–⑦ are the hook’s writes in order; ⑧ and ⑨ are the thread moves: the process first, then single threads, as ERGON_ISOLATED_CGROUP’s rule says and ergon’s cgroup kernel test does.
⑨ helper tids → cgroup.threads
⑧ pid → ergon-isolated/cgroup.procs
Isolated cpuset partition: the cgroup tree and the write order

3. io_uring

RuntimeDefault blocks io_uring (containerd issue 9320). Aeron’s C media driver does not use io_uring; the grant is for applications that do. It is a clone of the pod’s own seccomp profile with the io_uring_* calls allowed, never Unconfined, which the plugin refuses. The grant needs containerd 2.3 or later: earlier versions send NRI no seccomp policy, so the plugin refuses it there, and the Localhost profile is the way.

4. Admission

An exec probe starts a process inside the container on any CPU of its cpuset, the loop’s exclusive CPU included (k8s/nri-shared-cpus/README.md, Limits). A container with restartPolicy: Always is an injected sidecar: it shares the pod’s CPU budget and can run on the hot core.

The policy refuses both on pods labelled ergon.io/latency: "hot". It also requires a priorityClassName (eviction and preemption stop a hot pod mid-trade) other than ergon-helper and with a value above 100, the ergon.io/shared-millicpus resource, and the required-plugins.noderesource.dev annotation naming the plugin. Every form of that key NRI reads (/container.<name>, /pod) must name it too, as a plain list of quoted names with nothing after it.

A PriorityClass is cluster-wide, so keep ergon-hot out of other namespaces with a ResourceQuota (k8s/nri-latency-pods/README.md, item 4).

httpGet, tcpSocket and grpc readiness probes are fine: they run from outside the container.

5. Devices

The NIC’s PHC (/dev/ptp*) for clock work, and on x86 /dev/cpu_dma_latency so a pod can cap C-states. The PHC is granted only when the node’s ptp setting allows it ("off", the default, refuses the annotation), and read-only: a device cgroup rule denies write, so even root in the pod cannot step the NIC clock. That needs containerd 2.2 or later; older runtimes drop the rule, so the grant is refused there. The cap’s effect is not measured here, and a spinning core never idles, so treat the grant as access, not a latency win. On arm64 the plugin ignores the cpuqos annotation (k8s/nri-latency-pods/README.md, item 5).

Deliberately not built

itemwhy
real-time scheduling (SCHED_FIFO)not measured here. RT throttling (kernel.sched_rt_runtime_us, 950,000 of 1,000,000 µs by default, sched-rt-group) can take the CPU away. ergon-tune T7 warns on a real-time policy
SR-IOV VF per podNitro guests have one ENA per ENI; there are no in-guest VFs
a netns-sysctl writer pretending the knobs are per-netnsbusy_poll/busy_read are global; gro_flush_timeout and napi_defer_hard_irqs are per-netdev sysfs; rmem_max is not writable in a non-init netns. The node sets them (node-checks.md)
an IRQ DaemonSet that pins the latency pod’s NIC IRQs to the shared CPUsIRQs on a CPU that also runs other work are not measured here. The kept-CPU default stays

RTPRIO is granted as a limit only on the latency-pods path. That plugin never changes a scheduler policy, and the e2e asserts PID 1 stays SCHED_OTHER.

Node setup

The full check list is k8s/nri-latency-pods/node-checks.md. The short version:

settingvalue
Kubernetes>= 1.33 (the labs ran 1.36)
kubeletcpuManagerPolicy: static; reservedSystemCPUs = the IRQ CPU(s) plus the shared CPUs; x86 full-pcpus-only
strict-cpu-reservationoff (on, it empties the shared pool)
kernel>= 6.7, cgroup v2 (cpuset.cpus.exclusive is what the partition writes, and it is 6.7; a vendor backport of that file also works, because the plugin reads the file, not the version). Also nohz_full, rcu_nocbs, isolcpus=managed_irq on the exclusive CPUs, never the shared ones. 6.2 is enough for the shared CPUs only
transparent_hugepagenever
fair serverruntime 0 on each isolated CPU at every boot, kernel 6.12+ (shared CPUs). Nothing real-time may run there
net.core.rmem_max / wmem_maxat least Aeron’s AERON_SOCKET_SO_RCVBUF / SNDBUF when raised (hft)
net.core.busy_poll / busy_readunset (global; not measured here). Busy-poll per socket (SO_BUSY_POLL) instead
containerd>= 2.2, NRI on, the default validator on

Why not AKS: it has no supported way to change containerd (so an NRI plugin cannot be installed) and no reservedSystemCPUs list. Everything here needs one of those. The target is EKS on AL2023.

The two labels

They are different on purpose.

labelwherewhat reads it
pod ergon.io/latency: "hot"every latency podthe validating policy (extension 4)
namespace ergon.io/latency: "true"the latency namespacethe mutating policy (it reads namespaceObject)

Deployment

A busy-spinning thread is only as fast as its host. Start with Kubernetes HFT tuning: one table of every setting, where it goes (node or pod) and its evidence.

pagefor
Kubernetes HFT tuningstart here: the settings table, copy-paste blocks, three checks
AWS hosts, x86 and Gravitonhow to apply each node setting on a VM or node
Kuberneteswhole cores, no CPU quota, SMT off, what the node needs before kubelet
Java for Archive and Clusterthe JVM and Aeron settings for Archive and Cluster
Latency podsthe five grants a normal pod cannot make
Shared CPUsk8s/nri-shared-cpus: exclusive CPUs plus the node’s shared ones, checked with ergon-tune and ergon-cpus explain
Clockswhich clock to read, and time sync on the node

Glossary

Host, Kubernetes and Java terms:

termwhat it ispros / cons, when it matters
C-statehow deeply an idle CPU sleepsdeeper saves power but wakes later. A spinning core never idles; cap the IRQ CPU (hosts)
timer tick, RCU callbackskernel work on every CPU: a regular timer interrupt; deferred clean-upisolcpus keeps tasks off, nohz_full stops the tick, rcu_nocbs moves the callbacks (settings)
interrupt affinity, irqbalancethe CPUs an interrupt may run on; irqbalance is a daemon that moves interrupts aroundstop irqbalance, pin interrupts to housekeeping, pin again after every NIC reset
IOMMU passthroughIOMMU: the unit that checks which memory a device may reach. Passthrough (iommu=pt; Graviton iommu.passthrough=1) skips it for the host’s own driversneeded by some kernel-bypass drivers on metal; harmless on a VM
NUMA nodea group of cores and the memory nearest themkeep a pod’s CPUs and devices on one
KSM, NUMA balancingkernel background work: merging identical pages; moving pages nearer the CPU that uses themKSM merges only memory marked mergeable (MADV_MERGEABLE), which Aeron does not mark; NUMA balancing matters only with several NUMA nodes. The EKS node turns both off. Not measured here
spin testspin on every CPU for two minutes; note any that stall 300 µs or morea node-level check: a pod cannot choose its cores. Not measured here
-march, -mcpu, target-cpucompiler options that build for one CPU: -march, -mcpu (C), target-cpu (Rust). On AArch64 only -mcpu sets the coreGraviton: without them, gcc calls a library helper for each atomic add
clocksource=tsc, tsc=reliableboot options: the kernel keeps time with the CPU counter, and tsc=reliable turns its runtime checks offit turns the kernel’s TSC checks off: bare metal only, after measuring the TSC against a PTP/PHC reference, never on a VM (Kubernetes)
wall clock, NTP, PTPthe time of day (UTC), kept right by chrony over the network (NTP) or from a hardware clock (PTP)pro: matches other hosts and NIC stamps. Con: a correction can step it back; time intervals with quanta or Instant
kubeletthe agent on each Kubernetes node that starts pods and gives them CPUs, memory and devicesit must be told to give whole cores
Guaranteed QoSa pod whose requests equal its limits on every resourceonly these, with whole CPUs, get cores of their own from the static CPU manager
SMT (hyper-threading)two logical CPUs on one physical core, sharing its execution resourcesa pod with cpu: 1 shares the core with its twin. Turn SMT off on x86 latency nodes: one CPU is then one core, as on Graviton
CPU quota (CFS quota)a container’s CPU limit as the kernel applies it: at most the quota of CPU time in each 100 ms perioda busy-spinning thread runs at the cap; when it is used up the kernel stops the whole container until the period ends. On kubelet 1.33+ the quota goes away by itself for a container with exclusive CPUs; do not turn it off for the whole node
static CPU manager, topology managerkubelet policies: whole cores for Guaranteed pods; a pod’s CPUs and devices on one NUMA nodewith full-pcpus-only, no hyperthread is shared with another pod
cpusetthe CPUs a pod may run onpin each busy thread to its own CPU from it (Cpus_allowed_list)
DaemonSetone pod on every matching nodefor example, one media driver per latency node
device plugina node service that offers devices to pods as a resourcefor example, NICs for kernel bypass
taint, toleration, nodeSelectora taint keeps pods off a node unless the pod tolerates it; a nodeSelector sends a pod to labelled nodestogether: only latency pods (and the DaemonSets that must run there) land on latency nodes
LimitRange, ResourceQuotanamespace defaults and caps: a LimitRange gives every container a default CPU request and limit; a ResourceQuota caps the namespacean unlabelled pod cannot then ask for half a node (keep other pods in check)
PriorityClasshow important a pod is: a higher class preempts a lower onegive latency pods a high class and the rest a low one
hostPatha directory of the node, mounted into a podhere, the node’s hugetlbfs for Aeron’s directory
hostNetworka pod on the node’s network, not the pod network’s virtual interfacetakes a kernel-UDP pod off that interface
Archive, ClusterAeron’s Java services. Archive records and replays streams; Cluster runs your service on several nodes that agree on one log (the consensus module)ergon is only a cluster client; these run on Java
Agronathe Java library of buffers and agents that Aeron is built onits use of jdk.internal.misc.Unsafe is why the JVM needs the first --add-opens
LTSa Java release with long-term support (17, 21, 25)run Archive and Cluster on 25
JITthe JVM’s compiler: it turns hot code into machine code while the program runscode-cache pressure can undo its work (deoptimise)
GC, barrierGC: the garbage collector, which frees objects no longer used. Barrier: the extra work it adds to the program’s memory accessesParallelGC is what Aeron’s scripts use: convention, not a measured collector A/B
safepointa pause in which every Java thread stopsevery one is logged with its cause to tmpfs (-Xlog:gc*,safepoint, Java)
duty cycleone pass of an agent’s work loop*.cycle.threshold=1ms counts each one over 1 ms, so stalls show
spya subscription that reads a publication on its own host, from its log buffer, not the networksee aeron.spies.simulate.connection (Java)
sparse file, pre-touchsparse: disk pages appear only on first write. Pre-touch: every page is faulted in at startno first-write page faults, but pre-touched terms count against a container’s memory limit

Busy-spin loop

One thread, pinned to one CPU, never sleeps. Each turn it polls every source once, does the application’s work, and fires due timers. Everything that can block or take long runs on another thread.

The turn

stepcallbounded by
1. network I/Oyour socket or kernel-bypass poll: receive, run the handlers, flush sendsthe backend’s read burst
2. Aeron insubscription.poll_fn(handler, FRAGMENT_LIMIT)FRAGMENT_LIMIT
3. Aeron outpublication.offer of what the handlers queuedstops at the first retryable error; the rest waits for the next turn
4. timersone TSC read (quanta) and a comparethe timer’s own work

The application is one struct the loop hands every event to. The loop owns the sources, the clock and the timers; the struct owns the state.

Animation, in words: two turns of the ring, with illustrative counts. Turn 1: network I/O reads two packets (at most the read burst), the handlers run and queue m1. Aeron in has five fragments waiting but FRAGMENT_LIMIT is 3, so it reads three and the other two stay in the image; the handler queues m2 and m3. Aeron out commits m1, then m2 gets BackPressured, a retryable error, so the loop stops offering and keeps m2 and m3. Timers read the TSC once and compare: nothing is due (clocks). Turn 2: the socket has nothing, so the read returns at once; Aeron in reads the two leftover fragments; Aeron out commits m2 then m3, in queue order; a timer is due and its work runs. Never in the loop: allocation (reserved before it), blocking calls, connects and TLS handshakes (a helper thread), and host checks (the housekeeping thread), those threads on a CPU other than the loop’s. Why it wins: each step is bounded and back-pressure carries over instead of waiting; on one Azure Cobalt VM with helpers off its CPU the loop measured p50 0.02 µs, p99.99 0.03 µs, max 4.81 to 5.52 µs, the max being the hypervisor’s 3.5 to 5.5 µs floor (shared CPUs). When it loses: it burns a whole CPU even when idle, and a cpu: 1 pod puts the helpers on the loop’s CPU. The animation shows order, not timings.

Never inside the loop

neverwhyinstead
a blocking call: file or socket I/O outside the poll, DNS, sleep, a lock, a channel recvthe thread stops until it returnsbefore the loop, or on the housekeeping thread
a connect or TLS handshakewaits on the peer and costs CPU each timea helper thread that dials and hands the connected socket over
poll_blocking, or add_* with a timeoutbusy-waits for the media driverbefore the loop; in it, the async poller’s poll() once a turn
allocationthe allocator can lock and faultreserve before the loop (VecDeque::with_capacity)
logging that formats and writesa write blocks when stdout is fulla bounded non-blocking queue to a logging thread
host checks, ThrottleWatch, FaultWatch, ClockWatcheach reads a file or asks the kernelthe housekeeping thread
Instant::now() or SystemTime::now() for durationsa vDSO call eachquanta::Clock (the TSC), calibrated before the loop (clocks)
creating a threadit inherits the loop’s CPU mask: it would run on the loop’s CPUbefore the loop pins itself
waiting for a retryable Aeron error to clearstalls every other sourcekeep the message, retry next turn

Start-up order

A new thread inherits its creator’s CPU mask. So the loop thread moves to the helper CPU first, creates every other thread there (housekeeping, the Aeron client conductor, logging), and only then pins itself to its own CPU.

podthe loopthe helpers (housekeeping, aeron-client, logging)
cpu: 1the only CPUthe same CPU: give production pods 2
x86 with SMT, cpu: 2one hyperthreadits sibling
Graviton, cpu: 2one corethe other core
exclusive CPUs plus the node’s shared CPUsthe exclusive CPU (ERGON_ISOLATED_CPUS)the shared CPUs, where the process starts (shared CPUs)

Housekeeping

The checks that must run again while the loop runs, every few seconds, on a thread off the loop’s CPU. Each reads what it opened before the loop:

watchfindsfix
ThrottleWatch (T9)the container’s CPU quota stopped ita Guaranteed pod, whole CPUs, the static CPU manager (checklist)
FaultWatch (T19)the loop took a page faultmlockall and write every buffer once before the loop
ClockWatch (T11, T12)time sync or the kernel’s clock source changedtime sync on the node (clocks)
  • Open the FaultWatch for the loop’s thread before the loop starts.
  • A loop that has not warmed up faults on its first turns: expect T19 warnings for them.
  • The other checks run once, before the loop (where the checks run).

The Aeron calls one by one: rusteron-client.

Kubernetes HFT tuning

Every latency setting in this guide, where it goes, and its evidence. Traced links to the nri-shared-cpus lab in this repository. Not measured here means the setting rests on kernel, vendor or Kubernetes documentation only. Node needs node-level access (boot line, kubelet, root on the host); a pod cannot set it. Pod works from the pod spec or the app.

Terms: deployment glossary.

This chapter is the list. It is not an image and it is not a second chart. The shared-CPU grant is Shared CPUs: public image ghcr.io/mimran1980/ergon-shared-cpus:0.1.6 and chart oci://ghcr.io/mimran1980/charts/ergon-shared-cpus version 0.1.6 (EKS AL2023 hot pods need kubeletConfigDir: EKS install). The refusal of an exec probe on a pod labelled ergon.io/latency: hot is the admission policy in Latency Pods. Hugepages, the isolated cpuset partition, io_uring seccomp and the NIC PHC are opt-in grants in that same image. The chart writes seccomp and ptp as "off". The kind sample k8s/nri-shared-cpus/examples/try installs the public chart, prints the shared-CPU grant on an unlabelled pod, and shows the two hot-pod refusals: the plugin’s (no isolcpus on kind) and the admission policy’s. Not yet run on kind. It does not measure the rows below.

Settings

settingwhat it doeswhereevidenceapply
CPU isolationkeeps tasks, the timer tick, RCU callbacks and new interrupts off the busy CPUsnodeNO_HZ, kernel-parameters.txt; traced: with the quiet-CPU settings below an isolated CPU’s max was 4.81 to 5.52 µs (nri-shared-cpus)boot line isolcpus=managed_irq,domain,<busy> nohz_full=<busy> rcu_nocbs=<busy> irqaffinity=<housekeeping> (hosts)
NIC queue interrupts off the loop’s CPU, irqbalance off, re-pinned after every NIC resetthe interrupt handler does not run on the loop’s CPUnodeENA’s driver source (ena_setup_io_intr); not measured herehosts
ENA moderation off: adaptive-rx off rx-usecs 0one interrupt per packet; no adaptive-moderation work on the polling CPUnodeENA driver, AWS Graviton performance runbook; not measured hereethtool -C <if> adaptive-rx off rx-usecs 0, again after every NIC reset
SMT off (x86)one Kubernetes CPU is one physical corenodesiblings share one core’s execution units; not measured hereEC2 CpuOptions ThreadsPerCore: 1, or nosmt (SMT off)
static CPU manager, full-pcpus-onlyGuaranteed whole-CPU containers get CPUs of their ownnodeKubernetes CPU management; not measured herekubelet block
reservedSystemCPUs = the housekeeping CPUssystem daemons stay off the exclusive CPUsnodesame Kubernetes page; not measured herekubelet block
no CPU quota on a busy containerthe kernel never stops the container mid-periodnode + podsched-bwc, Kubernetes PR #127525 (kubelet 1.33+); not measured here (tune/src/quota.rs T9)kubelet 1.33+, static CPU manager, Guaranteed pod, whole-number cpu. Not cpuCFSQuota: false (why)
Guaranteed QoS, whole-number cputhe only pods the static CPU manager gives exclusive CPUspodKubernetes CPU management page; not measured herepod block
each busy thread pinned to one CPU of the pod’s cpusetthe thread stays on its exclusive CPUpodnot measured heresched_setaffinity from Cpus_allowed_list (busy-spin loop)
an io_uring SQPOLL thread on its own CPUthe kernel’s polling thread does not share the loop’s corepodnot measured herepin it to a CPU of the pod’s own outside the shared CPUs (shared CPUs)
transparent hugepages neverno khugepaged (it runs under madvise too), whose lru_add_drain_all runs a kworker on every CPU with queued pagesnodetraced: it was an isolated CPU’s only context switch and its 16.25 µs max (nri-shared-cpus)transparent_hugepage=never on the boot line, or never into /sys/kernel/mm/transparent_hugepage/enabled at boot
fair server off on the isolated CPUsno 1 s deadline-server timer kicking them (a nohz kick and a reschedule IPI) and keeping their tick onnodetraced, kernel 6.12: 56 kicks a minute with gaps to 14.1 µs, then 0 after (nri-shared-cpus)echo 0 > /sys/kernel/debug/sched/fair_server/cpu<N>/runtime for each isolated N, at every boot after debugfs is mounted (not persistent; kernel 6.12+). Only where nothing real-time runs on those CPUs: not with SCHED_FIFO
node events out of trading hourslru_add_drain_all callers (block-device ioctls, systemctl daemon-reload and generators, mlock, page migration) and BPF loads (systemd units, container starts with seccomp, SSH logins) reach every isolated CPUnode (operations)traced: a systemd daily timer gave a 40.60 µs max and one context switch (nri-shared-cpus)systemd timers moved off trading hours, no pod churn and no SSH logins on the node during trading
Aeron directory on a sized 2 MiB hugetlbfs, AERON_FILE_PAGE_SIZE=2097152, AERON_TERM_BUFFER_SPARSE_FILE=falseno 4 KiB page faults on the log buffersnode (pool, mount) + driver podhugetlbpage; not measured here. An unsized hugetlbfs reports no free space, which Aeron’s storage check refuses (aeron_fileutil.c:952-959 in rusteron-media-driver 0.2.11)hosts; the three variables in the driver pod’s env
AERON_CLIENT_PRE_TOUCH_MAPPED_MEMORY=truea client faults its mapped terms in at startpod (client)aeronc.h:170 (rusteron-client 0.2.11); not measured herepod block
net.core.rmem_max, wmem_max ≥ Aeron’s socket bufferslets the kernel grant AERON_SOCKET_SO_RCVBUFnodefunctional, not latency: the driver refuses a window larger than the granted SO_RCVBUF (aeron_driver.c:407-456, rusteron-media-driver 0.2.11). Aeron’s default is 128 KiB (aeron_driver_context.c:191); only a raised buffer, such as 2 MiB, needs itsysctl -w net.core.rmem_max=16777216 net.core.wmem_max=16777216
automatic NUMA balancing offno balancing page faults on pinned threadsnodenot measured heresysctl -w kernel.numa_balancing=0
topology manager single-numa-nodea pod’s CPUs and devices on one NUMA nodenodeKubernetes topology manager docs; not measured herekubelet block
the CPU that takes the NIC interrupts capped at C1 (intel_idle)an interrupt does not wait for that CPU to wake from C6nodecpuidle; not measured here. acpi_idle (AWS c7a): nothing deeper than C1 to cap. ergon-tune T20per CPU echo 1 > /sys/devices/system/cpu/cpu<N>/cpuidle/state<i>/disable for every state past C1, or pm_qos_resume_latency_us 1; intel_idle.max_cstate=1 caps every CPU. Write it at every boot
C-states capped at C1 on every CPU (x86)an idle housekeeping core wakes fasternodenot measured hereoptional; a spinning core never idles, so it reaches only the housekeeping cores
TCP autocorking offa small send goes out at once, not after the previous one’s transmit completes (TCP_NODELAY does not stop autocorking)pod netns, or node for hostNetworknet/ipv4/tcp.c tcp_should_autocork; not measured here. ergon-tune T21sysctl -w net.ipv4.tcp_autocorking=0; in a pod securityContext.sysctls, allowed by the kubelet’s --allowed-unsafe-sysctls
SCHED_FIFO on the loopreal-time prioritypodsched-rt-group: RT throttling can take the CPU away; not measured here. Not built into the Kubernetes pluginsthe app keeps SCHED_OTHER (latency pods)
ENA receive ring rx 4096room for burstsnodenot measured hereethtool -G <if> rx 4096
global busy polling (net.core.busy_read, busy_poll)every socket read on the host spinsnodeNAPI; not measured hereleave unset: it reaches every socket on the host; busy-poll per socket (SO_BUSY_POLL)
quiet-core spin testfinds CPUs the platform stallsnodenot measured here. A pod cannot choose its coresrun it on new nodes; cordon or replace noisy ones
no exec probes, no restartPolicy: Always sidecars on hot podsno probe process lands on the loop’s CPUpodan exec starts on any CPU of the cpuset (k8s/nri-shared-cpus/README.md, Limits); not measured herehttpGet/tcpSocket/grpc probes; the admission policy enforces it
both hosts in one cluster placement groupshorter network path between the pairnode (cloud)AWS docs; not measured herethe node group’s placement group
build for the CPU (-mcpu, target-cpu)Graviton: inline atomics instead of gcc’s outline helpersbuildnot measured herehosts
chrony on a PTP clockCLOCK_REALTIME stays close to UTCnodevendor docs; not a latency setting (Clocks)time sync

Copy-paste

Kubelet (EKS NodeConfig; k3s: Kubernetes):

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
cpuManagerPolicy: static
cpuManagerPolicyOptions:
  full-pcpus-only: "true"
reservedSystemCPUs: "0"          # the housekeeping cores
topologyManagerPolicy: single-numa-node
# cpuCFSQuota stays true: the kubelet drops it for exclusive CPUs (1.33+)

App pod: Guaranteed, whole cores, Aeron’s directory on the node’s hugetlbfs. AERON_FILE_PAGE_SIZE and AERON_TERM_BUFFER_SPARSE_FILE are read only by the media driver: set them on the driver’s pod.

apiVersion: v1
kind: Pod
spec:
  priorityClassName: <your latency class>
  containers:
  - name: app
    resources:
      requests: { cpu: "2", memory: 1Gi, hugepages-2Mi: 1Gi }
      limits:   { cpu: "2", memory: 1Gi, hugepages-2Mi: 1Gi }
    env:
    - { name: AERON_CLIENT_PRE_TOUCH_MAPPED_MEMORY, value: "true" }
    volumeMounts:
    - { name: huge, mountPath: /mnt/huge-aeron }
  volumes:
  - name: huge
    hostPath: { path: /mnt/huge-aeron, type: Directory }

Pin each busy thread to one CPU of the pod’s cpuset before the loop starts (busy-spin loop).

Check it

# 1. no CPU quota on the busy container
cat /sys/fs/cgroup/cpu.max               # expect: max 100000
grep throttled /sys/fs/cgroup/cpu.stat   # nr_throttled stays flat

# 2. the pod got whole cores of its own
grep Cpus_allowed_list /proc/self/status

# 3. the host: ergon-tune names each missing setting and its fix
ergon-tune --hot <busy CPUs>         # on the node

Under ERGON_HOST_CHECKS=require a caller of ergon-tune refuses to start while any check warns or a proof check stays unproven (ergon-tune). In a stock static-CPU-manager pod K2 stays unproven, so require refuses it (checks inside a pod).

  • A pod that uses the shared-CPU plugin: check the node with ergon-cpus explain before it starts (shared CPUs).

Open

  • Nothing here measures hugepages, the RX ring, NUMA settings or the CPU quota on latency.
  • The nri-shared-cpus lab traced its own maxima: after THP never and the fair server off, an isolated CPU on one Azure Cobalt VM took max 4.81 to 5.52 µs and no context switch in 60 s reps, the rest below the guest kernel (the hypervisor, 3.5 to 5.5 µs) (benchmarks).

More

pagefor
Kubernetesthe EKS node config, No CPU quota, SMT off, keeping other pods off the node
Hoststhe same settings on a VM, and how to apply each
Shared CPUshelper threads on the node’s housekeeping CPUs (k8s/nri-shared-cpus)
Latency podshugepages, io_uring, PHC devices on a pod (k8s/nri-latency-pods)

AWS hosts, x86 and Graviton

How to apply each node setting on a VM or a Kubernetes node. Which settings have evidence: Kubernetes HFT tuning.

Terms: deployment glossary.

Instances

Graviton first (c8g, c9g): no SMT, so one vCPU is one core. Any x86 is acceptable, c7a over c7i. Pick the smallest size with the cores the test needs; use Spot for tests.

platforminstance typesnotes
AWS Gravitonc8g.xlarge, c8g.2xlarge (Graviton4), c9g.xlarge, c9g.2xlarge (Graviton5)no SMT: a vCPU is a core
AWS x86c7a (AMD, no SMT), c7i.xlarge, c7i.2xlarge, c7i.4xlarge, c7i.metal-24xla c7i.4xlarge has 8 cores with SMT off
  • Put both hosts in one cluster placement group. Not measured here.
  • Compare only within one run and one host pair: two pairs of one instance type can differ.

Kernel command line

Keep the scheduler, the timer tick, RCU callbacks and new interrupts off every CPU but housekeeping. <busy> is the busy CPUs, <hk> housekeeping:

isolcpus=managed_irq,domain,<busy> nohz_full=<busy> rcu_nocbs=<busy> irqaffinity=<hk>

Effect: settings. Kernel reference: kernel-parameters, NO_HZ. On x86 isolate whole cores (SMT off, so one CPU is one core).

platformalso addwhy
AWS x86, bare metaliommu=ptfor a kernel-bypass driver that does not program the IOMMU; a VM has none
AWS Graviton, bare metaliommu.passthrough=1the same, on Arm
EKS latency node (x86)nosmt transparent_hugepage=never hugepagesz=2M hugepages=<n>; no C-state capKubernetes nodes. No cap: C-states

At every boot, kernel 6.12 and later: 0 into /sys/kernel/debug/sched/fair_server/cpu<N>/runtime for each isolated N, after debugfs is mounted (it is not persistent). The fair server’s 1 s timer otherwise sends each isolated CPU a nohz kick and a reschedule IPI and keeps its tick on (traced). Only where nothing real-time runs on those CPUs.

clocksource=tsc tsc=reliable turns the kernel’s TSC checks off: bare metal only, after measuring the TSC against a PTP/PHC reference, never on a VM.

Interrupts and the NIC

Interrupt moderation means the NIC waits to batch several packets into one interrupt: less CPU, more latency (ENA driver).

settinghowevidence
every movable interrupt on housekeeping, irqbalance stopped/proc/irq/*/smp_affinity_list, /proc/irq/default_smp_affinity; systemctl disable --now irqbalancenot measured here
NIC queue interrupts pinned again after every NIC resetENA puts each queue’s interrupt back on CPU i when the interface comes up (reset, ethtool -G/-L, a NIC handed back by a kernel-bypass driver). Re-pin on each link eventas above
ENA moderation offethtool -C <if> adaptive-rx off rx-usecs 0; ENA turns adaptive moderation back on when the interface comes up, so re-apply it with the pinsnot measured here
receive ringethtool -G <if> rx 4096not measured here
global busy pollingnet.core.busy_read, busy_pollit reaches every socket read on the host: leave unset and busy-poll per socket (SO_BUSY_POLL). Aeron’s media driver: hft

C-states

A C-state is how deeply an idle CPU sleeps: deeper saves power but wakes later. A spinning core never idles; the housekeeping core that takes the interrupts does.

hostsettingevidence
x86 VMcap only the IRQ CPU (ergon-tune T20)not measured here
x86 metalcap only the IRQ CPU (ergon-tune T20)not measured here
Gravitonnothing to setthe OS has no C-states to pick: an idle core waits for an interrupt (WFI)

Memory

settinghowevidence
transparent hugepages offtransparent_hugepage=never on the boot line, or never into /sys/kernel/mm/transparent_hugepage/enabledtranshuge; traced: khugepaged ran a kworker on an isolated CPU (nri-shared-cpus)
2 MiB hugepage poolhugepagesz=2M hugepages=<n> on the boot line, or vm.nr_hugepagesAeron’s hugetlbfs (and any kernel-bypass driver) draws from it
Aeron’s directory on a sized hugetlbfsmount -t hugetlbfs -o pagesize=2M,size=1G nodev /mnt/huge-aeron; on the media driver AERON_FILE_PAGE_SIZE=2097152, AERON_TERM_BUFFER_SPARSE_FILE=falsewithout size= Aeron sees no free space and refuses every log buffer (hft)
net.core.rmem_max, wmem_max16 MiBneeded only when Aeron’s socket buffers are raised above the kernel’s limit (hft)
automatic NUMA balancing offsysctl -w kernel.numa_balancing=0not measured here (one-node lab hosts)

Time

chrony on the Amazon Time Sync Service (169.254.169.123), or on the ENA’s PTP clock. Configuration: time sync.

CPU layout

One physical core per role. SMT is off on x86 latency nodes (SMT off), so one CPU is one core:

corex86 (SMT off)Graviton (no SMT)
housekeeping: interrupts, Aeron’s conductor, client conductorsCPU 0CPU 0
application, busy-spinningone CPUone CPU
media driver senderone CPUone CPU
media driver receiverone CPUone CPU
  • io_uring SQPOLL: its kernel thread spins, so give it a CPU of the pod’s own, not the loop’s SMT sibling (not measured here).
  • Name one CPU per core. thread_siblings_list still lists the offline twin; use the lowest id of each core. AWS numbers x86 siblings N and N + cores.

Build for the CPU

  • x86: rusteron builds Aeron’s C with -march=native unless RUSTERON_C_MARCH names another, so build the media driver on, or for, the instance type it runs on. For an image that runs on several types, name a baseline such as x86-64-v2 (armv8.2-a on Graviton), never the build host’s CPU.
  • Graviton: Rust with RUSTFLAGS=-Ctarget-cpu=neoverse-v2 (Graviton4), neoverse-v3 (Graviton5) or native; C with CFLAGS=-mcpu=.... Without it, Ubuntu’s and Debian’s gcc call a library helper for each atomic (gcc’s -moutline-atomics default on AArch64). On AArch64 -march sets only the architecture; -mcpu sets the core. Latency effect not measured here.

Check it

ergon-tune runs these checks, at start-up or as the ergon-tune command on the node, and prints each finding with its fix.

Clocks

Which clock to read for timestamps and durations, and time sync on the node.

Which clock for what

needreadwhy
a timestamp written anywhere: the wire, a log, storageCLOCK_REALTIME: std::time::SystemTime::now()UTC. Every thread and process on the host reads the same kernel clock, through the vDSO when the clock source is the counter (T12)
a duration or timer in one processquanta: Clock::now(), or Clock::raw() then Clock::delta_as_nanos()reads the CPU counter, scaled by one calibration per process against CLOCK_MONOTONIC; without a usable counter it reads CLOCK_MONOTONIC (quanta-0.13.0 src/lib.rs:333-344). Do not compare quanta values between processes: each calibrates on its own
a duration off the hot pathstd::time::InstantCLOCK_MONOTONIC: never goes back
flowchart TD
    Q["What are you measuring?"]
    Q -->|"a stamp on the wire, a log or a row"| R["CLOCK_REALTIME"]
    Q -->|"a duration or a timer in this process"| C["quanta, the CPU counter"]
    Q -->|"a duration off the hot path"| I["Instant, CLOCK_MONOTONIC"]

Not minstant for portable code: it reads the counter only on Linux x86 and x86_64. On every other target, Graviton and macOS included, it reads SystemTime, a wall clock that can go back (minstant-0.1.7 src/lib.rs:71-82).

Rules

  • Do not subtract two CLOCK_REALTIME stamps for a duration: chrony or an admin can step the clock back.
  • Build the quanta Clock before the loop. Its first calibration busy-waits (quanta’s limit: 200 ms, src/lib.rs:198), and quanta::Instant::now() calibrates a global clock on first use.
  • Do not stamp with a *_COARSE clock: it moves once a kernel tick (1–10 ms, by CONFIG_HZ).
  • A one-way time between two hosts is only as good as both hosts’ time sync. Use the same time source on every host that compares stamps.

Aeron’s clocks

Aeron keeps its own clocks (aeron_clock.c:91-136 in the Aeron tree shipped with rusteron-client 0.3.6). The driver’s agents read a cached copy (aeron_clock_cache_t).

Aeron APILinux sourcereturns
aeron_nano_clock()CLOCK_MONOTONICns since boot
aeron_epoch_clock()CLOCK_REALTIME_COARSEms since the Unix epoch, one kernel tick resolution
aeron_clock_cache_tboth, cachedas of the last refresh

Aeron::nano_clock() and Aeron::epoch_clock() read Aeron’s time; rusteron has no setter for them.

Set up time sync

Set it on the node: a pod shares the node’s CLOCK_REALTIME.

  • AWS: chrony on the Amazon Time Sync Service. Not systemd-timesyncd: it keeps no error bound.

    server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4
    makestep 0.0001 3
    

    For PTP-grade time: an instance type with a PTP hardware clock (EC2 PhcSupport), the ENA PTP clock enabled (in-tree ENA from Linux 6.17: devlink enable_phc; Amazon’s driver: phc_enable=1), then:

    refclock PHC /dev/ptp_ena poll 0 delay 0.000010 prefer
    server 169.254.169.123 iburst minpoll 4 maxpoll 4
    makestep 0.0001 3
    

    The service smears leap seconds: remove any leapseclist or leapsectz line.

  • A host with another PHC (a NIC or hypervisor clock): chrony on it (refclock PHC /dev/<device>; for a NIC’s clock also linuxptp’s ptp4l and phc2sys).

  • x86 and Graviton are set up the same way.

Check it with ergon-tune: T11 (how CLOCK_REALTIME is kept: PTP-grade, NTP or unsynchronised, and its error bound) and T12 (the kernel’s clock source) before the loop, then ClockWatch::check from housekeeping. On the node: chronyc tracking.

Kubernetes

A busy-spinning pod needs what a busy-spinning process on a VM needs: a whole core per busy thread, interrupts elsewhere, no page faults. Kubelet has to be told to give it that. The settings below apply to any low-latency pod; the node examples are EKS on Amazon Linux 2023 with self-managed nodes.

Terms: deployment glossary.

The kubelet and pod settings are the same on x86 (c7i) and Graviton (c8g, c9g). Graviton’s kernel arguments: hosts.

Latency checklist

Use a dedicated node pool, tainted so only latency pods land there (keep other pods in check).

Node (kubelet and host):

  1. SMT off on x86, so one Kubernetes CPU is one physical core, the same as on Graviton (SMT off).
  2. cpuManagerPolicy: static with full-pcpus-only: "true": Guaranteed pods get whole cores of their own.
  3. reservedSystemCPUs: the housekeeping cores, the same ones the kernel’s boot line leaves out of isolation.
  4. topologyManagerPolicy: single-numa-node: a pod’s CPUs and devices on one NUMA node.
  5. No CPU quota on the latency containers: kubelet 1.33 or later (the labs ran 1.36), cpuCFSQuota left at its default true. Do not set cpuCFSQuota: false: it removes every pod’s CPU limit on the node (why).
  6. The host settings under the kubelet: isolated cores, interrupts on housekeeping, transparent hugepages off, hugepages (hosts).

Pod:

  1. Guaranteed QoS: requests equal limits for every resource, in every container.
  2. A whole-number CPU request on every busy-spinning container. With SMT off, one CPU is one core.
  3. Each busy thread pinned to its own core from the pod’s cpuset, under SCHED_OTHER (SCHED_FIFO: settings).
  4. On CRI-O only: the annotations in No CPU quota. containerd (EKS, k3s) ignores them.

Check:

  1. At start: call ergon-tune’s t9_cpu_quota before your loop; T9 warns about a CPU quota.
  2. While it runs: nr_throttled stays flat (verify). In your own loop, call ergon-tune’s ThrottleWatch::check from housekeeping.

Nodes

Kubelet gives Guaranteed pods whole cores of their own (the static CPU manager) and keeps a pod’s CPUs and devices on one NUMA node (the topology manager). The EKS node’s NodeConfig, with $reserved the housekeeping CPUs (0 on a c7i.4xlarge: one CPU is one physical core, because SMT is off):

apiVersion: node.eks.aws/v1alpha1
kind: NodeConfig
spec:
  cluster:
    name: $cluster
    apiServerEndpoint: $endpoint
    certificateAuthority: $ca
    cidr: $cidr
  kubelet:
    config:
      cpuManagerPolicy: static
      cpuManagerPolicyOptions:
        full-pcpus-only: "true"
      reservedSystemCPUs: "$reserved"
      kubeReservedCgroup: ""
      systemReservedCgroup: ""
      topologyManagerPolicy: single-numa-node
      topologyManagerScope: pod
      memoryManagerPolicy: None
  • full-pcpus-only: whole physical cores, never one hyperthread shared with another pod. With SMT off it is a safety net.
  • kubeReservedCgroup and systemReservedCgroup are emptied because kubelet rejects reservedSystemCPUs while they are set.
  • memoryManagerPolicy: None: a c7i.4xlarge has one NUMA node. On a multi-socket type, revisit it.
  • cpuCFSQuota is not set: it stays true, so every pod keeps its CPU limit. The kubelet drops the quota itself on a container with exclusive CPUs (No CPU quota).

What the node needs before the kubelet starts:

whenwhat
once, then one reboot before kubeletkernel command line: nosmt, every CPU but the reserved core isolated, interrupts on that core, no C-state cap (evidence), transparent_hugepage=never, 2 MiB hugepages, so kubelet’s first start advertises hugepages-2Mi
every boot, before kubeletinterrupts on housekeeping, re-pinned on each link event; irqbalance, KSM, NUMA balancing off; THP off; rmem_max/wmem_max 16 MiB; Aeron’s directory on a sized hugetlbfs

Leave clocksource to the kernel. A forced clocksource=tsc tsc=reliable turns the kernel’s TSC checks off: use it only on bare metal, after the TSC has been measured as the same across cores against a PTP/PHC reference. Never on a VM.

Kubelet’s reserved CPUs and the kernel’s housekeeping CPUs are the same set: interrupts and system daemons stay off the pods’ cores. Label and taint the dedicated nodes (keep other pods in check).

SMT off

SMT (hyper-threading) runs two logical CPUs on one physical core. They share the core’s execution resources: a pod with cpu: 1 shares a core with its twin, and its latency follows what the twin does. Turn SMT off on x86 latency nodes, so one Kubernetes CPU is one physical core, as on Graviton, which has no SMT.

wherehow
EC2, virtual machinethe node group’s launch template: CpuOptions with CoreCount (the type’s default core count) and ThreadsPerCore: 1. Both fields are required; there is no extra charge. Not on bare metal (EC2 takes no CPU options there). EC2 will not change threads per core on T2, C7a, M7a, R7a, Apple silicon Mac or Graviton. C7a, M7a, R7a and Graviton already run one thread per core
EC2 bare metal, self-managedthe kernel’s nosmt on the boot line. Before the kubelet’s first start, writing off to /sys/devices/system/cpu/smt/control works too: write it, then delete /var/lib/kubelet/cpu_manager_state (the CPU manager state lists the old CPUs, and the kubelet crash-loops without the delete)
self-managed, k3snosmt on the kernel command line
  • With ThreadsPerCore: 1 the instance runs half its usual vCPU count (a c7i.4xlarge: 8 cores, 8 vCPUs, not 16). Size pods and quotas for cores.
  • thread_siblings_list still lists the offline twin. Name one CPU per core (the lowest id) in reservedSystemCPUs and in kernel arguments.
  • Check it on the node: /sys/devices/system/cpu/smt/active reads 0.

Pods

  • Guaranteed QoS with whole cores: requests equal to limits on every resource, and a whole-number CPU request.
  • Pin each busy thread to its own core from the pod’s cpuset. Read it from Cpus_allowed_list in /proc/self/status; in a privileged container /sys/fs/cgroup/cpuset.cpus.effective lists every host CPU. One logical CPU per physical core, and Aeron’s client conductor off the busy cores.
  • Hugepages as a resource (hugepages-2Mi), Aeron’s directory from the node’s hugetlbfs as a hostPath, and AERON_CLIENT_PRE_TOUCH_MAPPED_MEMORY=true on clients.
  • Handle SIGTERM. Kubelet stops a pod with it; a PID 1 with no handler ignores it until SIGKILL, closing nothing.
  • Privileged only where needed: a kernel-bypass driver that maps the NIC and locks hugepages. A client that only reaches the media driver through Aeron’s directory is not.
  • hostNetwork: true takes a kernel-UDP pod off the pod network’s virtual interface. Not measured here.

Keep other pods in check

A dedicated node pool only works if nothing else lands there.

  • Taint the latency nodes (NoSchedule) and let only latency pods and the DaemonSets that must run there tolerate it: the CNI, kube-proxy, the node agent, a log collector, the media driver. Everything else stays off.
  • A LimitRange per namespace with a default CPU request and limit for containers, and a ResourceQuota for the namespace. An unlabelled pod then cannot ask for half a node.
  • Small CPU requests and limits on the DaemonSets that stay (log collectors, a metrics agent): a limit keeps a burst off the latency cores. Give both; a limit with no request still lets them burst up to it.
  • PriorityClass: one high class for latency pods, a low one for the rest. A latency pod then preempts, not the other way round.
  • Kubelet 1.33 or later with the static CPU manager: only a Guaranteed whole-CPU container loses its quota; everything else keeps its CPU limit (No CPU quota).

strict-cpu-reservation (kubelet policy option, GA in 1.35): by default the shared CPU pool includes reservedSystemCPUs, so a Burstable pod or a fractional sidecar can run on the reserved CPUs. strict-cpu-reservation: "true" keeps everything that was not given those CPUs off them. Use it only when nothing but the system (and threads you pin there yourself) may use them: it breaks anything that needs the shared pool by default, such as a fractional sidecar in a latency pod or a helper thread left on the shared pool. The shared-CPU NRI plugin (ghcr.io/mimran1980/ergon-shared-cpus:0.1.6; chart oci://ghcr.io/mimran1980/charts/ergon-shared-cpus version 0.1.6) lends shared CPUs from reservedSystemCPUs to a pod’s helper threads and expects the default, so leave strict-cpu-reservation off while using it.

No CPU quota

  • A CPU quota (Linux’s CFS bandwidth control) lets a container’s threads run for at most the quota in each 100 ms period. Kubernetes sets it from the container’s CPU limit.
  • A busy-spinning thread uses its core all the time, so it runs at the cap. When the container’s other threads push it over, the kernel stops every thread in it until the period ends: a stall of milliseconds.
  • A pod has a quota of its own too: the sum of its containers’ limits. From inside a container, only cpu.stat.local shows it.
cpu.max holds two numbers in µs: the quota, then the period. max means no limit. In each period the kernel lets all of the cgroup’s threads together run for at most the quota; both cases below use a 100 000 µs (100 ms) period.
Spinner thread
running
stopped
running
stopped
running
stopped
Quota left
(50 ms per period)
Spinner thread
running
running
running
Second spinner
running
Child process
running
Quota left
(200 ms per period)
How ergon-tune sees it
ThrottleWatch::check, from housekeeping every few seconds, reads cpu.stat.local first and cpu.stat only when that grew, and reports “throttled in {t} of the last {p} periods”.
The pod’s quota: a second, outer budget
The pod has a quota of its own, the sum of its containers’ limits. A container cannot see its pod’s cgroup: only cpu.stat.local (Linux 6.6 and later) shows the pod’s quota stopping it.
Fix: cpu.max = max
No budget, so the spinner never stops. Per the Kubernetes docs, kubelet 1.33+ drops the quota for a container with exclusive CPUs (static CPU manager, a Guaranteed pod, a whole-number CPU request). Never cpuCFSQuota: false: it is node-wide.
spinner thread running
other threads running
stopped by the kernel (throttled)
quota left in this period
Case A · cpu.max = 50000 100000 · 0.5 CPU per 100 ms period
0 ms
100 ms
200 ms
300 ms
Quota left now
The spinner alone uses the quota up 50 ms into every period, and the kernel stops the whole cgroup for the other 50 ms. After 300 ms, in ideal arithmetic (not a measurement): nr_periods 3, nr_throttled 3, throttled_usec about 150000.
Case B · cpu.max = 200000 100000 · 2 CPUs per 100 ms period
0 ms
100 ms
200 ms
300 ms
Quota left now
Thread mix illustrative. The spinner alone spends half the quota and is never stopped. In the second period a second spinner joins and a child process runs from 140 ms: three CPUs empty the quota at 180 ms, and the kernel stops all of them, the spinner too, until the period ends (here 20 ms; up to 100 ms). After 300 ms, in ideal arithmetic: nr_periods 3, nr_throttled 1, and throttled_usec grows by the stopped time.
CPU quota: how a busy-spinning container gets stopped

What the kubelet writes:

casecontainer cpu.maxpod cpu.max
default (cpuCFSQuota: true), no exclusive CPUslimit × period: 200000 100000 for 2 CPUsthe sum of the containers’ limits
kubelet 1.33+, a container with exclusive CPUsmaxmax when any container has exclusive CPUs
a sidecar with a fractional CPU in that podstill capped: 50000 100000max
cpuCFSQuota: false (the whole node: do not)maxmax
  • Exclusive CPUs need all three: cpuManagerPolicy: static, a Guaranteed pod, and a whole-number CPU request on the container. Kubelet 1.33 is the first that then drops the quota.
  • Do not set cpuCFSQuota: false. It is node-wide: it removes the CPU limit of every pod there, log collectors and system pods too, and they then run unlimited on the shared CPUs. The kubelet’s own behaviour above is enough, and it only touches the containers with exclusive CPUs.
  • Kubelet 1.31 and 1.32 (EKS extended support) always set the quota. Use 1.33 or later (the EKS verification ran 1.36).
  • Changing cpuManagerPolicy: drain the node, stop the kubelet, delete /var/lib/kubelet/cpu_manager_state, start the kubelet. Without the delete, the kubelet crash-loops.

The kubelet config file:

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
cpuManagerPolicy: static
cpuManagerPolicyOptions:
  full-pcpus-only: "true"
reservedSystemCPUs: "0"     # the housekeeping cores (one CPU is one core)
topologyManagerPolicy: single-numa-node
# cpuCFSQuota is not set: it stays true, so every pod keeps its CPU limit.

EKS, Amazon Linux 2023: nodeadm writes its defaults to /etc/kubernetes/kubelet/config.json and spec.kubelet.config to the drop-in /etc/kubernetes/kubelet/config.json.d/40-nodeadm.conf, and runs the kubelet with --config-dir on that directory, so the kubelet merges the drop-in over the file. Put the NodeConfig in the launch template’s user data, as a MIME part with Content-Type: application/node.eks.aws. The full one, with the cluster fields, is in Nodes. The shared-CPU plugin reads both for its hot-pod check with hostContract.kubeletConfigDir: EKS install.

apiVersion: node.eks.aws/v1alpha1
kind: NodeConfig
spec:
  kubelet:
    config:
      cpuManagerPolicy: static
      cpuManagerPolicyOptions:
        full-pcpus-only: "true"
      reservedSystemCPUs: "0"

EKS, Bottlerocket: in the user data (TOML). Reboot after changing the policy. It has reserved-cpus and cpu-manager-policy-options too, but no feature gates. Leave cpu-cfs-quota-enforced at its default true.

[settings.kubernetes]
cpu-manager-policy = "static"

k3s: in /etc/rancher/k3s/config.yaml, or as a KubeletConfiguration drop-in under /var/lib/rancher/k3s/agent/etc/kubelet.conf.d/.

kubelet-arg:
  - "cpu-manager-policy=static"
  - "reserved-cpus=0"

CRI-O (OpenShift): the kubelet settings above are enough. CRI-O can also drop the quota per pod, but only with the high-performance runtime class (OpenShift’s Node Tuning Operator makes performance-<profile>), a Guaranteed pod and whole CPUs. containerd ignores these annotations, so they are safe in a shared manifest.

metadata:
  annotations:
    cpu-quota.crio.io: "disable"
    cpu-load-balancing.crio.io: "disable"
    irq-load-balancing.crio.io: "disable"
spec:
  runtimeClassName: performance-<profile>

Verify

On the node:

kubectl get node <node> -o jsonpath='{.status.nodeInfo.kubeletVersion}'   # 1.33 or later
kubectl get --raw /api/v1/nodes/<node>/proxy/configz \
  | jq '.kubeletconfig | {cpuCFSQuota, cpuManagerPolicy, cpuManagerPolicyOptions, reservedSystemCPUs}'

cpuCFSQuota reads true (or is absent: that is the default).

In the pod:

cat /sys/fs/cgroup/cpu.max            # max 100000
grep throttled /sys/fs/cgroup/cpu.stat
cat /sys/fs/cgroup/cpu.stat.local     # Linux 6.6+: counts the pod's quota too
  • nr_throttled and throttled_usec stay flat while the pod runs. Read them twice, a minute apart.
  • In Prometheus, cAdvisor’s container_cpu_cfs_throttled_periods_total stays flat.
  • ergon-tune: call T9 at start and ThrottleWatch::check from your loop’s housekeeping.

Checks inside a pod

A pod sees the host’s CPU, interrupt and memory files but its own network namespace. ergon-tune reports the network settings it cannot read there as unknown, never as a warning. Run the NIC checks on the node, or in a pod on the host’s network. T9 reads the container’s own cgroup; the pod’s quota shows only in cpu.stat.local (verify).

Under ERGON_HOST_CHECKS=require, a caller refuses a stock static-CPU-manager pod: K2 cannot prove exclusive CPUs from the kubelet’s cpuset, so it reports unknown. An isolated cpuset partition, as the latency pods plugin grants, passes it (ergon-tune).

Java for Aeron Archive and Cluster

ergo-aeron-cluster is only a client. The cluster (consensus module, clustered services, Archive) runs on Aeron’s Java, as does an Archive beside a C media driver. This page: which Java, and the JVM and Aeron settings for latency, for Aeron 1.54.3 (the release ergon pins). Each setting comes from Aeron’s own scripts, benchmarks or wiki (sources); none has a latency A/B here.

Terms: deployment glossary.

Which Java

UseJavaWhy
Run Archive and Cluster25: Eclipse Temurin 25 (LTS)The newest LTS in Aeron 1.54.3’s CI (17, 21, 25); ergon’s cluster harness runs on it in CI. eclipse-temurin:25-jre covers amd64 and arm64 (Graviton); Debian 13 ships openjdk-25-jre-headless.
Oldest that works17Aeron compiles its classes with --release 17.
Newest GA release, 27Runs, but not recommended27 is not an LTS release and is not in Aeron’s test matrix.
Build Aeron’s jars from sourceJDK 25 (17 to 27 work)Aeron’s Gradle (9.9.2) runs on 17 to 27. Any JDK makes Java 17 bytecode. Or skip Gradle, as ergon’s tests do: aeron-all-1.54.3.jar on Maven Central holds Archive, Cluster and the samples.

The eclipse-temurin:25-jre image has neither wget nor curl. Fetch the jar with a checksummed ADD:

FROM eclipse-temurin:25-jre
ADD --checksum=sha256:b801d0ef08aebddbeabd4363a05b83a1754fb6bacba186beb90403b295efacab --chmod=644 \
    https://repo1.maven.org/maven2/io/aeron/aeron-all/1.54.3/aeron-all-1.54.3.jar /aeron-all.jar

Ready-made settings

Two settings files, both tested by cluster-test-harness/tests/jvm_settings.rs: the JDK takes every option without a warning, every property is one Aeron’s sources name (Aeron ignores a misspelt one), and a cluster node started with both serves a client.

java @aeron.jvm -cp aeron-all-1.54.3.jar \
    io.aeron.cluster.ClusteredMediaDriver low-latency.properties cluster.properties

@aeron.jvm is a java argument file. Archive, ArchivingMediaDriver, ClusteredMediaDriver and ClusteredServiceContainer load every properties file named on their command line, so low-latency.properties and your cluster settings go there (or pass each as -D<name>=<value>).

Adapt two settings in cluster-test-harness/jvm/aeron.jvm: the heap (-Xms2g -Xmx2g) is a placeholder, so size it for your clustered service’s state (Archive alone needs far less); the log goes to /dev/shm, which only Linux has.

# JVM options for Aeron Archive, Cluster and the Java media driver, as a java
# argument file: `java @aeron.jvm -cp aeron-all.jar <main class>`. For Java 17
# and newer; run it on Java 25. cluster-test-harness/tests/jvm_settings.rs
# starts a cluster node with it and round-trips a message through it.
# Sources: Aeron's aeron-samples/scripts/java-common and cluster scripts, and
# the aeron-io/benchmarks scripts/run-java.

# Agrona reaches jdk.internal.misc.Unsafe: without this, IllegalAccessError.
--add-opens java.base/jdk.internal.misc=ALL-UNNAMED
# Archive CRC32 checksums reach into java.util.zip.
--add-opens java.base/java.util.zip=ALL-UNNAMED

# Archive, Cluster and the driver allocate nothing in steady state: the
# collector with the cheapest barriers.
-XX:+UseParallelGC
# A fixed heap committed at start. Size it for the clustered service's state.
-Xms2g
-Xmx2g
-XX:+AlwaysPreTouch
# Room enough that code-cache pressure never deoptimises hot code.
-XX:MaxMetaspaceSize=1g
-XX:ReservedCodeCacheSize=1g

# Every collection and safepoint with its cause, written by a background
# thread to tmpfs. %p is the process id.
-Xlog:async
-Xlog:gc*,safepoint=info,arguments=info:file=/dev/shm/aeron-jvm-%p.log:time,uptime,level,tags:filecount=4,filesize=16m

-Djava.net.preferIPv4Stack=true
# No bounds checks in Agrona's buffers. Read once, when the class loads: it
# must be set here, not by the application.
-Dagrona.disable.bounds.checks=true

cluster-test-harness/jvm/low-latency.properties:

# Aeron Archive and Cluster properties for latency, Aeron 1.54.3. Every spin
# or noop thread keeps a core at 100%: give each one an isolated core, or keep
# Aeron's default backoff. Pass the file as an argument to Archive's,
# ArchivingMediaDriver's or ClusteredMediaDriver's main (they load properties
# files named there), or each line as -D<name>=<value>.
# cluster-test-harness/tests/jvm_settings.rs runs a cluster node with them.

# Archive: a thread each for the conductor, recorder and replayer (the default
# DEDICATED mode), none of which sleeps.
aeron.archive.threading.mode=DEDICATED
aeron.archive.idle.strategy=spin
aeron.archive.recorder.idle.strategy=noop
aeron.archive.replayer.idle.strategy=noop

# Consensus module and clustered service: never sleep.
aeron.cluster.idle.strategy=noop

# Log buffers written out when created and faulted in when mapped, so the
# first write to a page is not a page fault. Costs start-up time and every
# term's memory up front. Aeron's benchmarks keep the defaults (sparse, no
# pre-touch) instead.
aeron.term.buffer.sparse.file=false
aeron.pre.touch.mapped.memory=true

# Thread names short enough for Linux's 15 characters (aeron-ar-rec,
# aeron-ar-rep, aeron-ar-cnd, aeron-cl-cm, aeron-cl-cs-0), so each hot thread
# can be found and pinned by name. The classic default names
# (archive-recorder, consensus-module-0-0, ...) are cut short.
aeron.thread.naming=new

# Count every duty cycle over 1 ms (default 100 ms), to see stalls.
aeron.archive.conductor.cycle.threshold=1ms
aeron.archive.recorder.cycle.threshold=1ms
aeron.archive.replayer.cycle.threshold=1ms
aeron.cluster.cycle.threshold=1ms
aeron.cluster.service.cycle.threshold=1ms

The JVM options

OptionWhySource
--add-opens java.base/jdk.internal.misc=ALL-UNNAMEDRequired. Agrona 2.x reaches jdk.internal.misc.Unsafe; without this option the JVM fails with IllegalAccessError.Aeron’s scripts and build.gradle
--add-opens java.base/java.util.zip=ALL-UNNAMEDRequired once Archive checksums are on (aeron.archive.record.checksum); without it they throw InaccessibleObjectException.Aeron’s scripts and build.gradle
-XX:+UseParallelGCArchive, Cluster and the driver allocate nothing in steady state. The choice is convention, not a measured collector A/B: every Aeron script uses it.every Aeron script
-Xms = -Xmx, -XX:+AlwaysPreTouchThe heap never grows, and every page is faulted in at start rather than on the hot path.benchmarks
-XX:MaxMetaspaceSize=1g, -XX:ReservedCodeCacheSize=1gCode-cache pressure never deoptimises hot code.benchmarks
-Xlog:async, -Xlog:gc*,safepoint=info,...Every pause and safepoint is logged with its cause, by a background thread, to tmpfs.benchmarks (to /dev/shm); -Xlog:async is ergon’s addition
-Djava.net.preferIPv4Stack=trueThe Java driver uses IPv4 UDP sockets.benchmarks, wiki, build.gradle
-Dagrona.disable.bounds.checks=trueTurns off the bounds checks in Agrona’s buffers. It is read once, when the class loads, so it belongs on the command line.low-latency.properties, benchmarks

The Aeron properties

PropertyDefaultWhy
aeron.archive.idle.strategy=spin, aeron.archive.recorder.idle.strategy=noop, aeron.archive.replayer.idle.strategy=noopbackoffThe Archive’s conductor, recorder and replayer never sleep. Each one needs an isolated core.
aeron.cluster.idle.strategy=noopbackoffThe consensus module and the clustered service both read this property.
aeron.term.buffer.sparse.file=false, aeron.pre.touch.mapped.memory=truesparse, no pre-touchThe first write to a page of a log buffer does not take a page fault. Aeron’s own sources disagree here: its low-latency.properties sets both, while its benchmarks keep the defaults. Pre-touching charges every mapped term to the process’s memory, and so to a container’s limit. With the C media driver, the driver’s own setting is AERON_TERM_BUFFER_SPARSE_FILE.
aeron.thread.naming=newclassicGives thread names short enough for Linux’s 15 characters, so each hot thread can be pinned by name (see below).
aeron.archive.*.cycle.threshold, aeron.cluster.cycle.threshold, aeron.cluster.service.cycle.threshold = 1ms100 msCounts every duty cycle longer than 1 ms, so stalls are visible.

These settings are left at their defaults:

  • aeron.archive.file.sync.level and aeron.archive.catalog.file.sync.level stay at 0: writes go to the OS page cache only. 1 adds fdatasync and 2 adds fsync. Keep the catalog’s level at least the archive’s. Level 0 survives a process dying and loses whatever is still in the page cache if the machine does. In a 3- or 5-member cluster another member’s log covers that loss, so 0 is the usual choice. A single-member cluster’s quorum is one: its local log is the only copy, so raise both sync levels together there and pay the fsync.
  • aeron.archive.file.io.max.length stays at 1m.
  • aeron.archive.control.term.buffer.sparse stays at true.
  • aeron.spies.simulate.connection stays false. It is a media driver setting, which Aeron’s benchmarks set to true on their driver. It matters when an Archive records a network publication by spying and nothing else subscribes: with false the publication waits for a network subscriber before it is connected.

Pinning the hot threads

Java has no CPU-affinity setting. Aeron’s benchmarks start the JVM on the housekeeping cores with numactl --membind --cpunodebind --physcpubind. They then move each hot thread to an isolated core by name with taskset -p. With aeron.thread.naming=new the names are aeron-ar-cnd, aeron-ar-rec, aeron-ar-rep, aeron-cl-cm and aeron-cl-cs-<service id>:

pid=$(pgrep -f io.aeron.cluster.ClusteredMediaDriver)
for task in /proc/"$pid"/task/*; do
    case $(cat "$task/comm") in
        aeron-cl-cm) taskset -pc 4 "${task##*/}" ;;
        aeron-ar-rec) taskset -pc 5 "${task##*/}" ;;
    esac
done

Every spin or noop thread needs a whole isolated core of its own (see Hosts). On shared cores, keep Aeron’s default backoff.

Small or shared hosts

When the JVM shares its cores, or runs in a container with a few hundred MiB:

  • Keep the backoff idle strategies. A spinning thread on a shared core takes the core from everything else.
  • Serial GC (-XX:+UseSerialGC) is the one-core collector; its cost against ParallelGC here is not measured.
  • Set -Xms equal to -Xmx, and size -XX:MaxDirectMemorySize, -XX:MaxMetaspaceSize and -XX:ReservedCodeCacheSize. The container’s limit must cover all of them, plus thread stacks and native memory.
  • Leave aeron.pre.touch.mapped.memory off. Every term a pre-touching client maps counts against the container’s memory limit.

Options to leave out of older guides

  • -XX:+UseParallelOldGC: Java 17 and 25 refuse to start with it. Aeron’s wiki still lists it.
  • -XX:-UseBiasedLocking: deprecated with a warning on 17. Java 25 refuses to start with it.
  • -XX:+ZGenerational: Java 25 ignores it with a warning, and 27 refuses to start. ZGC is now generational only.
  • The sun.misc.Unsafe deprecation (JEP 471, JEP 498) and --sun-misc-unsafe-memory-access do not apply. Agrona uses jdk.internal.misc.Unsafe, which is why the first --add-opens is needed.

Optional: measure first

These options are not in Aeron’s sources:

  • -XX:+UseCompactObjectHeaders (a product option since Java 25, JEP 519) makes objects smaller.
  • -XX:+PerfDisableSharedMem stops the JVM writing its hsperfdata file under /tmp, at the cost that jps and jstat no longer see it.
  • Generational ZGC (-XX:+UseZGC) is only worth it for a clustered service that allocates, needs sub-millisecond pauses and has cores to spare.
  • Huge pages through the JVM (-XX:+UseTransparentHugePages, Linux only) cover only the heap, which is cold in steady state. Aeron’s hot memory is its mapped log buffers; size those with aeron.file.page.size on hugetlbfs, as Hosts describes.

In ergon’s tests

The cluster harness (ergo-aeron-cluster-test-harness) runs $JAVA_HOME/bin/java, else java on PATH. A java older than 17, or one that will not run, fails the test with its path and the fix. Every Java process it starts reads cluster-test-harness/jvm/test.jvm, which follows Aeron’s own test settings: checks on, nothing spins.

# JVM options of every Java process cluster-test-harness starts, as a java
# argument file (java @test.jvm). After Aeron's own test settings in its
# build.gradle: the checks stay on and nothing spins. aeron.jvm holds the
# production options, which tests/jvm_settings.rs tries.

# Agrona reaches jdk.internal.misc.Unsafe: without this, IllegalAccessError.
--add-opens java.base/jdk.internal.misc=ALL-UNNAMED
# Archive CRC32 checksums reach into java.util.zip.
--add-opens java.base/java.util.zip=ALL-UNNAMED

# A small fixed heap: Aeron keeps its buffers off the heap, and several JVMs
# share the machine.
-Xms256m
-Xmx256m
-XX:+UseParallelGC

# Agrona's bounds checks stay on, and a misaligned atomic access fails rather
# than tearing.
-Dagrona.disable.bounds.checks=false
-Dagrona.strict.alignment.checks=true
-Djava.net.preferIPv4Stack=true
export JAVA_HOME=$(/usr/libexec/java_home -v 25)   # macOS; on Linux, the JDK's directory
just fetch-aeron-jars
just test-aeron-cluster-harness

Sources

Troubleshooting

First, check the node. Run ergon-tune on it, or in a pod that mounts the node’s /, and fix every WARN:

ergon-tune --hot 2-7 --nic ens6               # on the node; --tcp, --busy-poll as the app does
ergon-tune --root /host --hot 2-7 --require   # in a pod with the node's / at /host

Each finding prints its fix. Latency symptoms the host causes (loop gaps, timer ticks, interrupts, page faults, quota) map to a check in ergon-tune: symptom, check, fix. The rest:

Aeron

symptomcheckfix
Aeron::new or start fails: no driveris the driver running; does $AERON_DIR/cnc.dat exist in the app’s containerthe same AERON_DIR in both containers, on a volume both mount; retry with a deadline while the driver starts
offer returns NotConnected and stays therepublication.is_connected(); the subscriber’s channel and stream idthe same channel and stream id on both sides; on UDP, endpoint= is the receiver’s address and its UDP port is open between the hosts
offer returns BackPressured for longdoes the subscriber poll every turn; ergo-aeron streams names the subscriber furthest behindpoll it every turn; a larger term-length on the channel only buys time
the driver does not start with AERON_DIR on hugetlbfsT23AERON_FILE_PAGE_SIZE=2097152 and AERON_TERM_BUFFER_SPARSE_FILE=false
Aeron’s CPU affinity settings have no effectT22the Aeron 1.54 names: AERON_THREAD_AFFINITY_USE_CPUSET_OFFSETS, AERON_THREAD_AFFINITY_FAIL_ON_VALIDATION_ERRORS
the Aeron directory is on a diskT4/dev/shm, a memory emptyDir, or a sized 2 MiB hugetlbfs
a crash after closingwas a handle used after its publication, subscription or client closedclose in order: claims and images, then publications and subscriptions, then the client

The loop thread

symptomcheckfix
a helper thread runs on the loop’s CPUps -L -o tid,psr,comm -p <pid>, taskset -pc <tid>create every thread before the loop pins itself (start-up order)
T1, T8 and T2 report nothing for the loopwas the loop’s CPU in the HotSetpin the thread first, then name its CPU in the HotSet
T19 warnings: the loop takes page faultsFaultWatchmlockall (CAP_IPC_LOCK) and write every buffer once before the loop; T3, T5, T14, T17 on the node
millisecond stalls; nr_throttled growsT9, ThrottleWatcha Guaranteed pod, whole CPUs, the static CPU manager (checklist)
stalls when the log is busydoes the loop format or write log lines itselfa bounded non-blocking queue to a logging thread

Kubernetes

symptomcheckfix
every pod labelled ergon.io/latency: hot is refusedthe plugin’s log; curl <plugin-pod-ip>:9466/readyzthe kubelet config mounted (hostContract.kubeletConfig); on EKS AL2023 also hostContract.kubeletConfigDir.enabled=true (shared CPUs)
a hot pod is refused after the node ran fine (reason node-contract)the plugin’s log names the drift: IRQs, the reserved set, a quota, isolationfix the node; on EKS a NIC attached after boot puts its IRQs on the shared CPU: move them to the IRQ CPU
the container exits with SIGILL at startthe image’s CPU tag against the node’s CPUbuild for a baseline CPU (x86-64-v2, armv8.2-a), or select nodes by instance family for a CPU-specific image (build for the CPU)
a K check warns (K1–K7)the finding says pod spec or nodeas the finding says (what it checks)
a DPDK process starts without its NICT24the NIC device plugin (not shipped here) must inject the three RUSTERON_DPDK_SENDER_* keys
latency good after boot, worse later (AWS)T2, N1an ENA reset undid them: re-apply from a link-event hook (interrupts and the NIC)

Contributing

Changes must be reproducible, wire-compatible and honest about what was verified.

Work from behaviour

For a generator or protocol change:

  1. Add a focused behavioural, compile-fail, wire-parity or allocation test.
  2. Run it and see it fail.
  3. Make the smallest coherent change.
  4. Run the focused test and the affected crate’s full checks.
  5. Run the benchmark gate when a generated or cluster hot path changes.

A substring test on generated source can supplement a behaviour test. It does not prove wire correctness, type-state order, error propagation or allocation behaviour.

Checks

CommandWhat it runs
just policytest-lane ownership and the suppression rules below, plus their self-tests
just preflightstale-lock check, fmt, clippy, policy self-tests, book fences, golden and reference --check
just check-productsergo-sbe and ergo-aeron-cluster only
just check-localrepository hygiene, fmt, clippy, the tests that need no Aeron jars (building ergo-aeron-tools still needs a JDK 17 or newer), and the exchange-example, cluster-ha-orderbook and cluster-rfq samples
just testthe full suite: fetches the pinned Aeron release jars and runs the Java cluster lifecycle, recovery and HA lanes. A missing dependency fails
just test-alljust test plus Miri and fuzz replay
just check-coveragecoverage against the checked-in baseline
just check-mutationmutation testing over parser, resolver, sizing and dynamic-tail code

just policy (so also just test), just preflight and CI first fail on a stale gitignored Cargo.lock (samples/*, sbe/fuzz, sbe/miri-fixtures): one that locks a crate older than the root Cargo.lock does, or resolves a crate’s dependency to a semver line the root lock does not have. CI resolves those locks fresh, so it never sees them. The message names the lock and the fix, cargo update --manifest-path <dir>/Cargo.toml.

scripts/check-ignored-locks.sh is a root-lock parity heuristic, not full Cargo freshness. It does not check crates that exist only in a nested lock, git or path sources, or whether a manifest and its lock agree. A nested lock that resolves fewer dependency lines than the root lock is not stale.

RUSTDOCFLAGS="-D warnings" cargo doc -p ergo-sbe --all-features --no-deps
RUSTDOCFLAGS="-D warnings" cargo doc -p ergo-aeron-cluster --no-deps

Test policy

test-lanes.tsv assigns every tracked test-bearing Rust file to exactly one lane. scripts/check-test-policy.sh rejects:

PatternWhere it looks
#[ignore].rs files
an ignore doc fence.rs doc comments (Markdown rust,ignore is allowed)
a test printing SKIP or Skipped:.rs files
--skip, --ignored, --include-ignoredjustfile, just/*.just, scripts/*.sh, workflows
if … cargo test/benchthe same control files
cargo test … || true, ; exit 0the same control files
[skip ci]-style markers, continue-on-error: true, any if: other than always()workflows

The policy cannot see a test that returns Ok early without printing those words. The RLValidator leg is not such a test. It is compiled only with --cfg ergon_rlvalidator (scripts/run-fix-sbe-conformance.sh). With that cfg, a missing suite, class directory or classpath fails the test, and so does a suite that is not at the commit in scripts/fix-sbe-conformance-pin.txt. just test does not pass the cfg, so the leg is absent from the default suite; just release and the weekly nightly.yml run it (just test-fix-sbe-conformance).

A failure seen while changing the repository is not a pass because it looks pre-existing. Fix it, or stop and report it as a blocker. Never make a lane green by filtering, ignoring, conditionally bypassing or only logging the failure.

CI

WorkflowWhat it runs
ci.ymlpolicy; lint and test jobs on ubuntu-24.04 (x86_64) and ubuntu-24.04-arm (arm64); Rust 1.99.0; Java 25 for the Aeron jobs; the coverage ratchet; the fixture crate as ordinary tests; benches compiled with --no-run, none run
cluster-compatibility.ymlthe cluster harness against Aeron 1.46.8 on Java 21, when the cluster crate, the harness, sbe/src/, a manifest, Cargo.lock, the toolchain pin, the Aeron jar pins or fetch script, or the recipes it runs change (scripts/check-workflow-paths.sh fails if the filter drops one)
nightly.ymlweekly (Sunday): the six ergo-sbe fuzz targets for 600 s (not inspect_bytes or inspect_filter), the fixture crate under Miri, and the FIX SBE conformance suite with the Java RLValidator (just test-fix-sbe-conformance, suite pinned in scripts/fix-sbe-conformance-pin.txt)
release.ymljust release-check, then just bench and just bench-cluster on ubuntu-latest, blocking

Mutation testing is manual; CI checks only its configuration, and the ratchet fails when mutation output is missing or empty. 32-bit x86 and big-endian s390x codec tests are not run in CI.

Performance

just bench           # after a change that can affect generated hot paths
just bench-cluster   # after a cluster session codec, offer, claim or egress change

just bench-cluster takes every invocation twice, arms in registration order and then reversed, because whichever arm of a Criterion group runs first is measured differently from the one after it. The gate combines the two orders, so with the default BENCH_REPEATS=5 expect 20 cargo bench runs. It then prints, for every arm, the sample count, mean, and the min, p50, p99, p99.99 and max of the batch means pooled over all of them (scripts/bench-cluster-report.py; a sample is one 10,000-operation batch’s mean, so these are not per-message tails), and every pair’s gate verdict as PASS, INCONCLUSIVE or FAIL. An inconclusive pair passes the gate but is not parity. Quote a ratio only beside that table, and give each max a cause.

The target is ergon / sbe-tool ≤ 1.00 on equal work. Ceilings, the gate’s pass/inconclusive/fail rules and the fairness rules: sbe/BENCHMARKS.md. Do not raise a ceiling. Do not copy benchmark numbers into docs by hand: book/src/project/performance.md is generated from benchmark artifacts (just perf-page). A docs-only change needs no benchmark run.

fairness_policy_test requires the SBE and cluster parity suites to use std::hint::black_box, assert correctness before timing, and keep the benchmark disclosure. Treat a large result as suspect until the benchmark is re-audited.

Error and example style

  • Public library APIs use crate-specific typed errors.
  • Tests and binaries may return Result<(), Box<dyn std::error::Error>>.
  • Prefer ? to unwrap or expect.
  • Treat schema-declared text strictly; keep binary fields as bytes.
  • Size message buffers from generated constants or length helpers.
  • Use the high-level cluster facade in consumer examples.

Documentation

  • The root README orients; crate usage goes in that crate’s README.
  • One sample inventory: samples/README.md. No per-sample READMEs.
  • A page that describes how the software behaves describes current, verified behaviour. A superseded number is not the current result.
  • Keep the record in the tree. The AI-assistance account, benchmark round write-ups, screenshots and release notes stay. Git history is not a substitute for that record. Dated plans and scratch task trees do not belong in the tree.
  • One page owns a fact; other pages link to it.
  • A book diagram (book/src/diagrams/) lists in book/diagrams.tsv every source its facts were checked against. A change to a listed source fails scripts/check-book-diagrams.sh: re-verify the diagram against the change, then --restamp it.

Versioning

Every crate is 0.x alpha. Any release may break the API, with no deprecation period and no compatibility shim. CHANGELOG.md records each break. This does not cover the wire: official SBE wire compatibility still outranks API convenience.

scripts/check-generated-public-api.sh (in just preflight and CI) diffs generated codec surfaces against api/generated/*.txt, so a surface change is reviewed, not forbidden. After a reviewed change: UPDATE_GENERATED_PUBLIC_API=1 cargo test -p ergo-sbe --test generated_public_api_test.

Package boundaries

The publication candidates are ergo-sbe, ergo-aeron-cluster, ergon-tune, ergo-sbe-inspect and ergo-aeron-tools (api/public-api-baseline.toml). Publish ergo-sbe first, then ergo-sbe-inspect, then ergo-aeron-tools. scripts/check-publish-set.sh (in just policy) fails when a published crate depends on an unpublished one, on a path without a version, or on an older version than a published sibling’s, or when the release recipe, workflow, dry runs or API manifest leave a crate out or publish it before its dependencies. A version bump therefore updates every version beside a workspace path with [workspace.package]: ergo-sbe and ergo-sbe-inspect in [workspace.dependencies].

Inspect the payloads before a release:

cargo package -p ergo-sbe --list --allow-dirty
cargo package -p ergo-aeron-cluster --list --allow-dirty
cargo package -p ergon-tune --list --allow-dirty
cargo package -p ergo-sbe-inspect --list --allow-dirty
cargo package -p ergo-aeron-tools --list --allow-dirty

Packages exclude integration tests, fixtures not needed at build time, benchmarks, Java harness code, application protocols, samples and internal plans. ergon-tune ships its library, the ergon-tune command and its README. ergo-sbe-inspect and ergo-aeron-tools ship src/, their README and the licence. Building ergo-aeron-tools with its default features (the publish verify build does) needs CMake, a C compiler, libclang and a JDK 17 or newer.

Publishing, tagging and announcing a release need explicit maintainer authorisation. Before an authorised release, a maintainer runs just release-check (see Verification & Release); the release workflow runs the same command before cargo release.

Git hygiene

  • Preserve unrelated working-tree changes and a dirty submodule.
  • Stage paths explicitly; do not use git add -A.
  • Do not rename the sbe, cluster or samples directories.
  • Use a short one-line conventional commit subject.

AI assistance: how ergo-sbe was built

ergo-sbe was developed with heavy AI assistance. Most of the implementation, tests, benchmarks, samples, and documentation were written by coding agents. I did very little direct coding.

I am saying that at the beginning because this is not a conventional project with a little autocomplete around the edges. If you do not want to use software written substantially by LLMs, stop here. This is probably not the right project for you.

That warning is not an apology, and this page is not marketing. It is a disclosure of:

  • why I chose this project;
  • what I knew before the models became involved;
  • what I asked the models to do;
  • what I did and did not review;
  • how the generated codecs were verified;
  • where the workflow worked and where it failed;
  • which tools and models were used;
  • what the work actually cost;
  • why the crate is still labelled experimental; and
  • what I would expect before using it in a financial system.

The short version is:

I supplied the SBE domain knowledge, requirements, API judgment, corrections, acceptance criteria, and release decisions. Coding agents supplied nearly all of the implementation. I reviewed the generated Rust API and output far more closely than I reviewed the syn/quote generator implementation. The observable output is constrained by extensive tests, live byte-for-byte comparisons with official sbe-tool Rust codecs, official fixtures, compile-fail proofs, allocation checks, and performance gates. That is strong evidence, but it is not a substitute for independent production use.

This account describes the initial intensive development period ending in July 2026. Prices, model names, repository state, and my process will change. Treat dated figures as a historical record, not a permanent promise.

Read this first

This article is long because “AI-assisted” is too vague to be useful on its own. If you only have a minute, these are the facts that should determine whether you continue evaluating the crate:

QuestionShort answer
How much was written by AI?Most of the implementation, tests, benchmarks, samples, and documentation. I did very little direct coding.
What was the human contribution?More than a decade of SBE experience, the product requirements, API judgment, domain corrections, acceptance criteria, and release decisions.
What received human review?Primarily the generated Rust API and source, encoded bytes, test failures, and benchmark results, not an exhaustive line-by-line audit of the syn/quote generator internals.
What independently constrains the output?Official sbe-tool byte-for-byte comparisons, Java-produced fixtures, upstream schemas, compile-fail proofs, property tests, exact-length checks, allocation tests, and performance gates.
Is it production-proven?No. It remains experimental 0.x software. Production users should validate their own schemas, versions, message shapes, and traffic.
What did development consume?Roughly one month of intensive work. The initial 0.1.0 release used approximately 14 billion tokens (estimated from provider dashboards). The combined ledger on 2026-11-05 is 86.98 billion tokens (86,979,781,620): each machine’s ccusage high-water mark (a Mac mini and a MacBook), with the Claude Code transcripts copied between them counted once. A run on either machine alone will not match that total (see cumulative token usage).
What did it cost?~$261 actual out-of-pocket (DeepSeek PAYG $77.39 + GLM plan $114 + subscriptions $70). The combined ledger’s own API-rate total is $24,273.94. The same measured mix, priced on one Anthropic model at the public card checked on 2026-10-21 with 5-minute cache writes, is $15,062.68 on Sonnet 5.5 and $30,125.35 on Opus 5.5. With my work Claude Enterprise subscription the Claude portion would be covered by the seat licence rather than per-token billing, so the real cost at work would be lower still. The single-provider what-if shows the input, output, and cache arithmetic.
Which model did most of the work?DeepSeek: V4 Flash handled much of the early UltraMode/subagent work; the later sequential development stayed primarily on V4 Pro.

Contents

  1. Cumulative token usage (since 2026-06-28)
  2. What-if: all tokens through a single provider
  3. Why this page exists
  4. What I was trying to build
  5. Why I chose it as an AI experiment
  6. Authorship
  7. What I reviewed, and what I did not
  8. The actual working loop
  9. How the project evolved
  10. What the Git history shows
  11. What did not work
  12. Verification
  13. Performance
  14. Unsafe code and the trust boundary
  15. Tools and models
  16. Long context, O(n²), and caching
  17. Observed usage and spend
  18. Pay-as-you-go comparison
  19. A practical playbook
  20. The personal experience
  21. Why the crate is experimental
  22. What production users should verify
  23. AI-assisted contributions
  24. Final assessment

Cumulative token usage (since 2026-06-28)

Per-model figures for Claude Code, Codex, and Grok Build CLI, summed over two machines: a Mac mini (called “the other machine” in the older notes below) and a MacBook. Each machine’s figure is a per-model, per-column high-water mark of its own ccusage reads. Both machines were last read on 2026-11-27. The Mac mini’s earlier mark comes from every ccusage snapshot committed to this file (2026-08-03, 2026-08-07, 2026-08-13, 2026-08-15, 2026-08-19, 2026-08-20, 2026-08-27, 2026-09-07, 2026-09-13 and 2026-09-14, plus the 2026-10-13 run); the MacBook’s from its reads on 2026-10-21. Claude Code transcripts from 2026-10-13 to 2026-11-03 exist on both machines, because the MacBook’s were copied to the Mac mini on 2026-11-03; those days count once. A ccusage run on either machine alone will not match this table.

ModelInputOutputCache CreateCache ReadReasoning OutputTotal TokensCost (USD)
claude-fable-5403,4851,349,25412,230,126487,557,778—501,540,643$802.28
claude-fable-5-278,987,0045,470,6751,998,55471,598,897—158,055,130$885.03
claude-haiku-4-5-2025100193631,021203,27910,487,325—10,722,561$1.56
claude-haiku-5-58848,527524,5182,020,110—2,593,243$0.17
claude-opus-4-8189,031554,7804,981,35997,619,868—103,345,038$100.90
claude-opus-513,758,2294,833,90137,960,9203,736,999,202—3,793,552,252$2,418.75
claude-opus-5-5369,831,505203,422,9471,858,738,90752,595,262,984—55,027,256,343$25,857.26
claude-sonnet-4-61,406233,671986,40034,920,711—36,142,188$19.90
claude-sonnet-589,0082,994,50131,612,8042,341,088,665—2,375,784,978$623.42
claude-sonnet-5-535,66214,011,591166,057,0642,909,768,582—3,089,872,899$854.99
deepseek-flash9,079,4275,080,386—3,204,345,088—3,218,504,901$28.02
deepseek-v4-flash52,791,36717,446,045—2,734,161,536—2,802,078,889$35.00
deepseek-v4-pro85,359,08721,733,136—24,546,493,056—24,653,585,279$551.30
glm-4.76,949,701760,380—268,436,096—276,146,177$35.37
glm-5.227,277,6183,460,625—2,274,775,808—2,305,514,051$644.86
gpt-5.57,380,642366,392—69,651,456105,36877,503,858$92.47
gpt-5.6-luna1,754,305188,525—54,281,984105,11656,329,930$36.18
gpt-5.6-sol60,170,1565,240,538—1,520,615,0402,617,7221,588,643,456$1,011.83
gpt-5.6-terra693,82034,722—7,463,16816,2298,207,939$4.37
gpt-6-astra12,112,650867,424—177,654,656231,434190,866,164$310.94
gpt-6.1-sol31,984,4623,248,064—834,639,744995,046870,867,316$237.06
gpt-6.2-astra90,4765,371—1,250,5601031,346,510$1.44
gpt-6.2-sol5,133,323261,667—96,031,74436,824101,463,558$30.17
grok-4.5-build10,030,758881,349—177,071,360—187,983,467$114.67
grok-4.6-build44,849,8923,100,656—812,446,592—860,397,140$293.80
grok-4.7-build58,890,2348,855,611—1,005,219,584—1,072,965,429$256.03
mimo-v2.6-pro73,484,7421,497,690—2,292,630,144—2,367,612,576$72.77
gpt-5.3-codex22,573,8842,873,034—786,800,5121,263,964813,511,394$217.63
gpt-5-codex9,351,684988,119—204,395,904689,664215,425,371$45.08
gpt-5.1-codex-max2,116,543122,477—45,743,36046,97648,029,356$11.63
gpt-5.41,517,76354,121—14,817,28024,11016,413,274$8.09
gpt-5701,63779,205—8,801,92051,7769,634,538$2.77
mimo-v2.6-flash34,783,7541,405,339—1,288,136,960—1,324,326,053$9.33
gpt-5.4-mini122,1024,288—434,5602,399563,349$0.20
Total1,022,496,381311,506,0322,115,293,931104,713,622,2346,186,731108,166,785,250$35,615.28

Notes:

  • The other machine’s baseline is a high-water mark, not a single run’s output. ccusage keeps no ledger: it recomputes totals by re-reading local session transcripts, and Claude Code deletes transcripts older than cleanupPeriodDays. A --since 20260628 query therefore loses its earliest days as time passes, so a later snapshot can report fewer tokens than an earlier one. That baseline is the per-model, per-column maximum across all eleven snapshots; since the tool can only under-report, that maximum is the best available lower bound. This MacBook’s 2026-10-21 read is added on top of that baseline. A second read the same day, filtered to --since 2026-06-01, is merged the same way: where it was higher, that column replaced this machine’s earlier figure; where it was lower, the earlier figure stays. The transcripts are different files, so each published row is the sum.
  • The 2026-10-13 run alone reported 57,084,644,123 tokens. Merging the snapshots recovered from this file’s git history adds 2,589,115,055 tokens the current run can no longer see. A later ccusage on one machine is added the same way. It does not replace this table.
  • In the 2026-10-13 snapshot: claude-opus-5-5, claude-sonnet-5-5, deepseek-flash, gpt-6.1-sol and grok-4.7-build. claude-opus-5, claude-sonnet-5, deepseek-v4-pro, gpt-6-astra and grok-4.6-build set new total maxima. Every other model’s maximum is held by an earlier snapshot; grok-4.5-build appears only in earlier snapshots.
  • Grok Build CLI rows come from ccusage grok, which extracts them from the Grok CLI session logs.
  • Antigravity and Gemini CLI are not in the table. The other machine had no observer sample, and its usage of those tools is still absent. This MacBook’s ccusage antigravity reports 290,048,735 tokens and $83.86 (2026-06-20 to 2026-07-05). ccusage gemini reports 553,921 tokens and $0.56 (November 2025, December 2025, and February 2026). Those reads are recorded here and were not added to the rows above.
  • Hermes and OpenCode are excluded: automation, not development work on this project. This MacBook had no Hermes transcripts. Its OpenCode total is 178,124,443 tokens and stays out of the table.
  • Codex reports cost per day rather than per model. On days that used more than one model, the day’s cost is split between them in proportion to their token share; token counts themselves are exact per-model figures from the tool. On the 2026-10-21 MacBook read, Codex totalTokens omits reasoning. The day’s cost was split on that totalTokens. Reasoning is then included in the Total Tokens column.
  • All costs are at enterprise/pay-as-you-go API rates observed by each tool. Subscription fees (Claude, OpenAI, Grok) are not included.
  • Sanity checks: the per-model column sums for the 2026-10-13 run reconcile exactly against each tool’s own reported totals (53,825,172,584 Claude Code + 2,019,689,986 Codex including 3,537,371 reasoning output + 1,239,781,553 Grok = 57,084,644,123), and the grand total is monotonic against the previously committed 25,853,122,297.
  • 2026-10-21 MacBook check, ccusage 20.0.40 with cached offline prices. The first read was the full local history: Claude Code 14,674,098,035 + Codex 1,458,109,013 + Codex reasoning 2,484,098 + Grok 266,056,280 = 16,400,747,426. Claude Code covered 2026-06-26 to 2026-10-21, Codex 2025-09-13 to 2026-10-21 (1,154,747,421 of those tokens are before 2026-06-28), and Grok 2026-10-14 to 2026-10-21. A later read the same day, npx ccusage@latest --since 2026-06-01 -b, reported every detected agent: 15,583,155,859 tokens and $5,108.42. Antigravity was 290,048,735 tokens and $83.86, the figure already recorded, and stays out of this table. Gemini CLI and OpenCode had no rows in that window. Claude Code’s token total was unchanged. Codex token columns for models with usage on or after 2026-06-01 matched the first read, including their reasoning. Codex before 2026-06-01 is outside that window, so those rows stay at the first read (gpt-5.3-codex, gpt-5-codex, gpt-5.1-codex-max, gpt-5.4, gpt-5, gpt-5.4-mini, and the earlier part of gpt-5.5). The unified report also repriced those same Codex tokens; that reprice was not applied, so the published Codex costs remain the daily split from the first read. Grok grew by 573,183 input, 250,829 output and 20,426,240 cache read (21,250,252 tokens; unrounded cost from $57.056 to $61.702). The MacBook ledger in this table is therefore Claude Code 14,674,098,035 + Codex 1,458,109,013 + Codex reasoning 2,484,098
    • Grok 287,306,532 = 16,421,997,678. Added to the other machine’s 59,673,759,178 this is 76,095,756,856. Unrounded costs are Claude Code $4,737.668, Codex $537.250 and Grok $61.702, together $5,336.62. The previous cost total was $14,394.52; combined $19,731.14. deepseek-v4-flash’s Total Tokens cell remains 2,320,059 below the sum of its own columns, as previously published.
  • 2026-11-05 reads: npx ccusage@latest daily -b (20.0.48) on the Mac mini, and the same unified daily report on the MacBook. The MacBook report’s rows reconcile exactly with its own Total row (23,931,907,711 tokens, all agents).
  • The copy. 1,518 Claude Code transcript files on the Mac mini were created at 11:31 on 2026-11-03 (UTC+8): the MacBook’s sessions active from 13:02 on 2026-10-13. From 2026-10-14 to 2026-11-02 the Mac mini’s Claude Code usage equals the MacBook’s per day and model, token for token, except 2026-10-15 and 2026-10-27, where the Mac mini holds slightly less. The Mac mini had no Codex or Grok usage in that window, and neither tool’s logs were copied. Those 21,770,555,386 Claude Code tokens count once, in the MacBook’s figures. The MacBook’s Claude rows for 2026-10-13 and 2026-11-03 are subtracted from the Mac mini’s read of those days, with their cost. The whole 2026-10-13 row is subtracted although only its afternoon was copied, so up to about 43 million tokens of that day may be missing. Like transcript cleanup, this can only under-report.
  • MacBook: per model and column, the larger of its 2026-10-21 figures and the new read up to 2026-10-22, plus the new read from 2026-10-23. The 2026-10-21 read already held part of 2026-10-22, so the split falls there. The MacBook adds 8,286,299,912 tokens and $3,422.62.
  • Mac mini: the larger of its 2026-10-13 high-water mark and the new read up to 2026-10-13, plus the new read from 2026-10-14 without the copied days. It adds 2,596,671,615 tokens and $1,120.18.
  • Cost: published costs stay as they are. Added tokens carry the cost the new read gives them; where a read up to a split date exceeds the earlier figure, the excess is priced at that segment’s average rate. The new reads price mimo-v2.6-pro at about $0.57 per million tokens, against about $0.018 in the 2026-10-21 read; the earlier tokens keep their earlier cost.
  • The new reads have no reasoning column. Reasoning output stays at its earlier figures, and a changed row’s Total Tokens is the sum of its columns, which carries 1,053,237 earlier reasoning tokens of gpt-6-astra and gpt-6.1-sol into Total.
  • Not added, as before: on the Mac mini, Gemini CLI 375,413,088 tokens ($183.59), Hermes 311,780,314, OpenCode 246,593,840, Antigravity 44,554,114 and ZCode 22,091,463; on the MacBook, Antigravity 290,048,735 (unchanged) and OpenCode 62,841,911 (2026-10-23 and 2026-10-24).
  • The grand total rises from 76,095,756,856 to 86,979,781,620 tokens and the cost from $19,731.14 to $24,273.94.
  • 2026-11-27 reads: npx ccusage@latest claude daily --json -b, and the same for codex and grok (20.1.2), on the Mac mini and on the MacBook, summed per model. Only Claude Code, Codex and Grok rows count, as before; Gemini CLI, Hermes, OpenCode, Antigravity, ZCode and OpenClaw are not added. The reads dropped older days again: the MacBook’s all-agent total is 23,128,940,145 tokens, below its 2026-11-05 read of 23,931,907,711, so no figure from the new reads replaces an earlier one. Both machines add only the days from 2026-11-06. The days to 2026-11-05 stay at the earlier marks. The 2026-11-05 read held only part of that day on the Mac mini (about 0.8 billion of its 3.27 billion Claude Code tokens, estimated from what the 2026-11-05 note added), so the rest of that day, about 2.5 billion tokens, is not counted. Like transcript cleanup, this can only under-report. No day from 2026-11-06 is on both machines with the same figures, so nothing is dropped as a copy.
  • The Mac mini adds 21,135,299,213 tokens and $11,318.41 (Claude Code, Codex and Grok); the MacBook adds 51,635,786 tokens and $22.93 (Claude Code and Codex; no Grok). Together 21,186,934,999 tokens, plus 68,631 Codex reasoning tokens that the new Codex reads report and that count in the row totals. Costs are the new reads’ own prices for those days. New rows: claude-fable-5-2, gpt-6.2-astra and gpt-6.2-sol. The new Grok read names its model grok-4.7; it is merged into grok-4.7-build.
  • The grand total rises from 86,979,781,620 to 108,166,785,250 tokens and the cost from $24,273.94 to $35,615.28.

What-if: all tokens through a single provider

This prices the cumulative table’s measured buckets on one Anthropic model. Rates are the public Claude API card checked on 2026-10-21 (model pricing). The result is a counterfactual. It is not an invoice, and it is not the ~$261 out-of-pocket spend.

Measured mix

The price uses the column sums. Those columns add to 86,982,101,679 tokens. The published total cell is 86,979,781,620, which is 2,320,059 lower, because deepseek-v4-flash’s Total Tokens cell is short of its own columns by that amount. Cache writes in this ledger are entirely Claude Code rows. Every other provider recorded cache reads and left cache create blank.

CategoryTokensShare of 86,982,101,679
Uncached input768,664,7920.88%
Output241,670,6980.28%
Reasoning output6,118,1000.01%
Cache writes1,021,205,6511.17%
Cache reads84,944,442,43897.66%
Column sum86,982,101,679100%

Cache reads plus cache writes are 98.83% of that sum. Output including reasoning is 247,788,798 tokens (0.28%).

One Anthropic model for every measured token

Assumptions, all stated so the arithmetic can be repeated:

  • uncached input at the model’s input price;
  • cache writes at the 5-minute cache-write price (1.25× input), which is the write Claude Code records;
  • cache reads at the model’s cache-hit price;
  • output and reasoning output both at the output price;
  • standard global API rates: no fast mode, no batch discount, no US-only 1.1× data-residency multiplier;
  • token counts held fixed. Claude 4.7 and later, including Opus 5.5 and Sonnet 5.5, use a tokenizer Anthropic says produces about 30% more tokens for the same text. That uplift is not applied here;
  • Haiku 5.5 bills a higher card when the prompt is over 100,000 tokens, counting input, cache writes, and cache reads toward that length. These sessions are long, so the over-100k line is the matching card. The under-100k line is the short-prompt card only.

Sonnet 5’s $2 / $10 per million input/output tokens, announced as introductory pricing through 31 August 2026, is now the standard price. The previously scheduled rise to $3 / $15 on 1 September 2026 did not happen. Opus 5.5 and Sonnet 5.5 cache hits are 0.05× input ($0.20 and $0.10 per million). Other Claude models on this list use 0.1×.

ModelInput $/MTok5m write $/MTokCache hit $/MTokOutput $/MTokTotal
Opus 5.5$4$5$0.20$20$30,125.35
Sonnet 5.5$2$2.50$0.10$10$15,062.68
Opus 5$5$6.25$0.50$25$58,892.80
Sonnet 5$2$2.50$0.20$10$23,557.12
Haiku 4.5$1$1.25$0.10$5$11,778.56
Haiku 5.5, prompts over 100k tokens$0.50$0.625$0.05$2.50$5,889.28
Haiku 5.5, prompts up to 100k tokens$0.10$0.125$0.01$0.50$1,177.86

Where each dollar comes from, at the 5-minute write price:

ModelUncached inputCache writesCache readsOutput incl. reasoningTotal
Opus 5.5$3,074.66$5,106.03$16,988.89$4,955.78$30,125.35
Sonnet 5.5$1,537.33$2,553.01$8,494.44$2,477.89$15,062.68
Opus 5$3,843.32$6,382.54$42,472.22$6,194.72$58,892.80
Sonnet 5$1,537.33$2,553.01$16,988.89$2,477.89$23,557.12
Haiku 4.5$768.66$1,276.51$8,494.44$1,238.94$11,778.56
Haiku 5.5, prompts over 100k tokens$384.33$638.25$4,247.22$619.47$5,889.28

One-hour cache writes are 2× input. Only the write column changes. Opus 5.5 becomes $33,188.97 and Sonnet 5.5 becomes $16,594.48.

The ledger’s own mixed-provider API total is $24,273.94. Sonnet 5.5 comes out lower because 97.66% of the measured tokens are cache reads and its cache hit is $0.10 per million. Opus 5.5 cache hits are $0.20 per million, so the same reads cost $16,988.89 and the all-Opus bill is $30,125.35. Opus 5 cache hits are $0.50 per million, which is why that line is $58,892.80. Out of pocket remains about $261.

Caveats

  1. Cache writes exist only on the Claude rows. DeepSeek, GLM, Codex, and Grok recorded cache reads and no cache-create column. Pricing those reads as Anthropic hits does not add the write that would have created the cache entry. A real all-Anthropic run would have paid those writes. They are not in this ledger, so they are not in the totals above.

  2. The cache-read share dominates the bill. 84.94 billion of the 86.98 billion column-sum tokens are cache reads. A project with shorter sessions would rank these models differently, because input and output prices would matter more than the cache-hit price.

  3. Token counts are held fixed. Another model can tokenise the same transcript differently, emit different output and reasoning, and keep a different cache-hit ratio. The Claude 4.7+ tokenizer note above is the documented case of that. These figures isolate the rate card.

The 14-billion-token comparison further down uses a July 2026 sample and the prices checked on 26 July 2026. It is not this ledger.

Choose the path that matches why you are here:

Why this page exists

SBE is widely used in financial systems. In that environment, code quality is not an aesthetic preference. A plausible-looking logic error can corrupt a message, misread a price or quantity, or fail only when a particular schema version or repeating-group shape appears in production.

AI has made software provenance much harder to judge. Two people can publish similar-looking libraries:

  1. a domain expert who has encountered the protocol’s failure modes for years;
  2. somebody with no practical knowledge of the domain who asked an LLM to generate a library and was impressed that it compiled.

The second person may honestly believe the result is excellent because they do not know what the model misunderstood. A reader should not have to reverse engineer which situation applies.

LLM-generated defects also tend to feel different from ordinary human defects. A human implementation often contains a typo, a missed branch, or a copy-and-paste error inside a design the author understands. An LLM can produce a coherent implementation of the wrong mental model. The code may be clean, consistent, documented, and comprehensively wrong about one domain invariant. That changes how it should be reviewed.

This page therefore exists so that an engineer, especially one responsible for money, can make an informed decision. Do not infer quality from the amount of code, the fluency of the documentation, or the fact that tests are green. Look at the verification evidence, the remaining trust boundaries, and the experimental status.

What I was trying to build

I have used SBE for more than a decade, including Java and Rust systems. The project idea predates this AI experiment.

Over those years I repeatedly saw the same classes of problem:

  • A new SBE user reads or writes positional data in the wrong order.
  • Repeating groups and variable-length data make buffer sizing easy to get wrong.
  • Java-style flyweights and parent hopping become awkward under Rust’s borrow checker.
  • A low-latency wire representation is valuable on a hot path, but it is unnecessarily unpleasant when application code simply wants a Boolean, decimal, owned DTO, or database record.
  • A partially completed encoder can be mistaken for a complete message unless the API makes that misuse impossible.

My desired API followed from those experiences:

  • wire order enforced at compile time;
  • no final byte slice or encoded length until all required tail fields have been written;
  • closure-based nested groups that work naturally with Rust borrowing;
  • exact buffer sizing for messages containing groups and variable data;
  • a fast flyweight path for latency-sensitive code;
  • optional conversions and domain DTOs for code that does not need to operate directly on the wire representation; and
  • official SBE wire compatibility as the non-negotiable contract.

Without coding agents, I estimated that the generator would take me roughly four to six months. I had previously written code generation by hand in another open-source project and knew how fiddly a large syn/quote implementation could become. My original plan was to wait until a long garden-leave period and build it manually.

Why I chose it as an AI experiment

I had a two-and-a-half-week holiday and wanted to improve from being a regular LLM user to understanding agentic coding properly: which models were useful for which jobs, how context affected them, how quickly subscription limits became the bottleneck, and whether the impressive multi-agent workflows shown in demos survived contact with a non-trivial codebase.

This project seemed unusually well suited to that experiment:

  • I already knew the domain and the behaviour I wanted.
  • The requirements were concrete; I did not need an LLM to teach me SBE.
  • Much of the implementation was mechanical but cumbersome code generation.
  • Official SBE has extensive schemas, fixtures, and tests.
  • The product of the generator is Rust source that I can inspect directly.
  • Wire bytes and benchmark results provide objective feedback.
  • If the model misunderstood an API, I could normally identify the problem quickly and show it the shape I wanted.

I had also seen a Jon Gjengset demonstration of an AI-assisted Rust porting exercise. It made this kind of project look worth trying.

The holiday work was intense. It was effectively all I was doing: at least eight hours and sometimes closer to fourteen hours on a day. An agent might run for 10, 20, or occasionally 30–40 minutes, during which I could do something else, but I stayed available to inspect its progress and intervene. The project was not finished in two and a half weeks. It expanded to roughly a month of heavy work, including subsequent evenings and weekends, because I added useful features and raised the quality threshold as the crate became closer to something I might genuinely use.

How the scope grew

Some capabilities were firm requirements from the beginning; others became practical only after I saw how quickly the generator could evolve.

  • Exact encoded length was something I had wanted for years, but I did not initially assume it would fit into the holiday scope. Once the agent could generate the repetitive machinery quickly, I decided it was worth doing properly.
  • Domain DTOs began as a nice-to-have and expanded when it became clear that they could make SBE useful outside the hottest latency-sensitive path.
  • Schema evolution was part of the intended protocol support.
  • The Aeron Cluster client began as a realistic consumer of the codecs rather than the main product. Focused samples later became a better way to exercise difficult API shapes.

The ease of generating experiments encouraged scope growth, but it did not make the verification free. Every added feature created more generated surfaces, tests, and benchmark work.

Authorship: what was mine and what was generated

I did very little manual implementation. Even when I saw the required code change, I usually described it to the active agent and let the agent edit the files.

That was partly deliberate. I found that mixing my own live edits with an agent’s existing context often made the agent less reliable. It continued from the version of a file it had already read unless I explicitly told it to reload and reconcile everything. The most successful workflow was to let the agent drive the edits while I drove the design and feedback.

The division was approximately:

AreaMy roleCoding-agent role
Problem and productChose the problem from practical SBE experienceNone
Domain behaviourDefined the required SBE behaviour and corrected misunderstandingsImplemented the behaviour described
API designSpecified the desired properties, inspected generated APIs, rejected awkward designsProposed Rust representations and iterated on them
GeneratorSpecified and reviewed generated output; did not deeply review every generator pathWrote nearly all syn/quote implementation
TestsChose important scenarios, inspected tests, ported the verification strategy from official SBEWrote and ran most test code
PerformanceRequired equal-work parity, personally ran and inspected benchmarks, rejected regressionsWrote harnesses, ran them repeatedly, diagnosed and revised regressions
Documentation and samplesSupplied the intent and judged whether examples represented a usable APIDrafted most prose and sample code
Release decisionsDecided what was acceptable and retained the experimental warningProvided recommendations, not authority

Design ideas that came from my SBE experience

The principal goals were not invented by a model:

  • Compile-time wire ordering. I wanted it because ordering mistakes were a routine real-world SBE support problem.
  • Exact encoded length. I wanted it because humans repeatedly miscalculate nested groups and variable data.
  • Closure-based groups. I had already used this pattern manually to avoid borrow-checker pain.
  • Converters and DTOs. I wanted application code to use types such as Rust bool and decimal values where direct wire access was unnecessary.
  • Checked constructors with private zero-check cores. I wanted fallible wrap / decode for every untrusted buffer, and a measured private hot-path core only after extent proof (public *_unchecked twins only if keep=true). What the crate ships now is the three tiers in Unsafe code and the trust boundary.
  • Unsafe only when justified. I asked the agents to test particular unsafe optimisations, measure them, and remove them when they did not matter.

The models helped explore implementations. For example, I asked how Rust could enforce ordering and discussed traits and type-state representations. A model proposed concrete named stage structs. That was a good implementation of my requirement and ultimately avoided a performance problem with generic stages.

For converters, I knew the user-facing capability I wanted but had not fully designed the API. The models proposed several shapes. Some were wrong or ugly; I showed the kind of calling code I wanted and refined the result.

This is the fairest summary: the domain requirements and product judgment were human-authored; the implementation and much of the Rust design exploration were AI-assisted.

What I reviewed, and what I did not

This distinction is essential.

I did not perform a comprehensive, line-by-line human review of the generator implementation. In particular, I did not deeply audit every syn/quote path that constructs the emitted source.

I had written this sort of generator manually before. It is fiddly, but it is also a task at which I had already seen LLMs perform well: provide a concrete Rust shape and ask the model to emit that shape for every schema case. My expected failure mode was not usually “the model cannot call quote!.” It was “the model has misunderstood what the generated API or wire behaviour should be.”

I therefore concentrated review on the generator’s observable product:

  • the generated Rust source;
  • whether the public API is clean and usable;
  • whether staged types make illegal orderings unrepresentable;
  • actual encoded bytes;
  • official SBE fixtures and official sbe-tool output;
  • exact-length results;
  • error behaviour on malformed or incomplete buffers;
  • allocations on intended zero-allocation paths; and
  • performance relative to official generated Rust codecs.

I could often inspect generated Rust and immediately see an incorrect offset, an awkward repeating-group API, an invalid stage transition, or unnecessary complexity. That feedback was much faster and more useful than mentally simulating a large code generator.

This means the project should not be described simply as “human-reviewed code.” A more accurate description is:

Human-directed, generated-output reviewed, and behaviourally verified, with generator internals substantially AI-authored and not exhaustively line-reviewed by a human.

The automated evidence reduces risk. It does not prove that an untested schema shape cannot expose a generator defect.

The actual working loop

The primary agent interface was Claude Code CLI, often connected to custom models rather than a Claude model. Claude Code was useful because I wanted to learn the tool used at work and because its endpoint configuration let me run DeepSeek and GLM through the same agent workflow.

The work ran on a Mac mini at home. I connected with JetBrains RustRover Remote Development, the Claude Code app, and ordinary SSH. I used Herdr, an agent-aware persistent terminal multiplexer, so the Claude Code session survived disconnects and I could reattach from another device.

This made long-running work convenient, but not unattended. There were two review modes:

  1. Output review. Let the agent finish a small change, generate codecs, run checks, and then inspect the resulting API and behaviour.
  2. Live intervention. Watch the edits and reasoning, stop the agent when the approach was visibly wrong, explain the correction, and let it continue.

A typical successful loop was:

  1. I describe one concrete behaviour or API improvement.
  2. The agent adds or updates focused tests.
  3. The agent changes the generator.
  4. It regenerates and compiles the Rust output.
  5. It runs relevant unit and parity tests.
  6. For hot-path changes, it reruns the benchmark gate.
  7. I inspect the generated API, bytes, failures, and benchmark result.
  8. I give a specific correction and repeat.

The short feedback loop mattered more than one-shot model intelligence.

How the project evolved

Looking back, the work divided into several recognisable phases. This matters because the workflow that appeared successful in the first phase was not the workflow that completed the project.

Phase 1: the spectacular greenfield demo

At the beginning, specifications, issues, subagents, and separate worktrees looked almost magical. There was no established architecture to collide with, so several agents could create apparently useful pieces at once. This is the part of agentic development that makes the best video: a blank repository becomes a compiling application while multiple streams of activity scroll past.

It was real progress, but it created the wrong expectation. Parallel output is not the same thing as an integrated design. As soon as type-state transitions, generator conventions, error handling, wire offsets, and generated API style became shared constraints, locally reasonable changes stopped composing.

Phase 2: shared invariants forced sequential work

The project became productive again when I reduced the unit of work and made the feedback loop mostly sequential. One agent changed one connected area, regenerated the codecs, ran the focused tests, showed me the result, and received a correction. This was less theatrical and much more effective.

At this stage I learned that I needed to inspect the artefact closest to the contract. For ergo-sbe, that was normally the emitted Rust, the calling API, the encoded bytes, or the benchmark, not the syntax-tree construction that produced it. I could identify a bad offset or ugly repeating-group API quickly in generated code. The same mistake was much harder to see by mentally executing hundreds of lines of syn and quote.

Phase 3: performance invalidated an elegant design

The first type-state design used generics (Encoder<State>) because I assumed the abstraction would be free after monomorphisation. It was elegant and enforced the ordering requirement, but the benchmark showed a meaningful encoding regression. A design can be type-safe, idiomatic, tested, and still fail the product requirement.

The LLM helped explain why the generated machine code differed and proposed concrete named stage types with a zero-sized H: HeaderState marker. I accepted the concrete representation because the measured result mattered more than abstract neatness. All 15 maintained parity comparisons passed at or below the 1.00× ceiling in the 0.1.8 release (both LTO profiles). From then on, benchmark parity became part of the definition of done for relevant changes. The gate as it stands now, including the exceptions and the A/A noise band, is sbe/BENCHMARKS.md under “The gate”.

Phase 4: cheap implementation expanded the product

Once the core generator was working, features that would have been too expensive in a four-to-six-month manual schedule became plausible. Exact encoded length, DTOs, converters, richer samples, schema-evolution cases, and more exhaustive generated APIs all grew during this period.

This is one of the genuine advantages of LLM implementation: it lowers the cost of trying a design. I could ask for a complete version, inspect the result, reject it, and try a different shape without feeling attached to the discarded code. The disadvantage is that every cheap feature creates an expensive verification and review obligation. Generated code is cheap; confidence is not.

Phase 5: hardening and disclosure

The final phase was less about visible capability and more about earning confidence: official fixture decoding, byte-for-byte dual encoding, multiple official schemas, compile-fail tests, exact-size matrices, allocation checks, unsafe audits, benchmark gates, documentation, and this disclosure.

The project crossed a line during this phase. It was no longer merely an exercise in learning agents. It had become a crate I wanted other SBE developers to evaluate. That raised the standard and is why the work continued past the holiday.

What the Git history shows

The commit history provides a useful independent record of how the project actually developed. It should not be treated as a measure of human effort: agents commit much more frequently than I would when working manually, and some commits are tiny formatting, test, or repair steps. It does, however, show the shape and sequence of the work.

The history snapshot ending at commit 85442ed on 26 July 2026 contains 976 commits after the initial main scaffold. The active codegen work began on 5 July and the history records:

  • 14 commits on 5 July;
  • 157 on 6 July;
  • 128 on 7 July;
  • 89 on 8 July;
  • 46 on 9 July;
  • 74 on 10 July; and
  • 41 on 11 July.

That is consistent with the intensity of the holiday period, but the more interesting evidence is structural. The history contains ten explicitly named worktree-agent or equivalent worktree merge commits. Every one of those occurred on 6 or 7 July. After that early experiment, the branch becomes overwhelmingly linear; the only much later merge was an ordinary remote tracking merge on 25 July. This is visible evidence of the transition I described: parallel subagents were exciting in the greenfield phase, then shared invariants pushed the development into a sequential loop.

The subjects also expose the sequence of technical lessons:

  • 5–6 July: scaffold the generator, create the roadmap, add baseline wire tests, CI, golden generation, upstream regression schemas, benchmarks, unsafe experiments, and early exact-length support.
  • 7–8 July: migrate more generator code to syn/quote, expand group and variable-data support, add property and conformance tests, and repeatedly repair the interactions between those features.
  • 9 July: benchmark-driven redesign from generic encoder states to non-generic concrete structs, followed by generated-shape regression tests.
  • 10 July: introduce concrete consuming decoder stages, compile-fail ordering proofs, zero-allocation checks, and broad generator coverage.
  • 11 July: restrict bytes and encoded length to complete stages, add nested message and converter workflows, and prove callback and stage ownership constraints.
  • 17–21 July: rerun multi-run benchmark matrices, deepen DTO/converter support, migrate the Aeron Cluster client to ergo-sbe, and harden Cluster behaviour and samples.
  • 22–24 July: rename the workspace to ergon, expand the L3 examples, build the staged exact-length API for uniform, ragged, nested, and variable-data shapes, and revisit checked versus unchecked performance.
  • 25 July: fix DTO conversion and ragged-length defects, complete Cluster reliability work, run Java interoperability tests, repair benchmark gates, and add broader generated-code safety tests.
  • 26 July: clarify documentation and packaging, add live byte-for-byte comparisons against checked-in official sbe-tool Rust codecs, close the multi-schema parity gaps, and publish this disclosure.

This is a messier and more credible history than a one-shot generation story. It contains reverts, merge repairs, performance regressions, benchmark redesigns, API replacements, small cleanup passes, and tests added after failures. It shows that the project was not produced by one prompt. It was produced through hundreds of short, observable corrections.

What did not work

Large parallel-agent plans

At the beginning I tried the impressive workflow often shown in demonstrations: a specification becomes issues, issues become parallel subagents and worktrees, and all the results merge together.

It looked extraordinary during the first greenfield days. Once the codebase contained shared generator invariants and interdependent API decisions, it ground to a halt. Agents made locally reasonable changes against different assumptions. The merge cost and coordination cost overwhelmed the parallelism.

For this project, meaningful work became mostly sequential. Parallel agents were useful only for genuinely independent investigation, not for several changes to the same evolving generator.

Long one-shot requests

“Implement this and come back in an hour” stopped working as complexity grew. The useful workflow required constant feedback. When the agent had freedom to invent a user-facing API, it often produced something technically plausible but ugly. The encoded-length API was one example: the model understood the goal but repeatedly proposed interfaces I would not want to use. Once I supplied a concrete calling shape, it could implement it.

Fabricated authority: the “SBE spec §4.1” incident (July 2026)

Model: GPT-5.6 Sol (OpenAI). Harness: Codex CLI v0.144.5. Session: 019f7f7d, 2026-07-20 12:26 UTC, from ~/RustroverProjects/ErgoSBE. Commit: bd3f7ce.

This was a frontier model: OpenAI’s top-tier offering at the time. I was expecting to find DeepSeek behind this when I traced the history. I was wrong.

One coding agent left a six-line comment in the code generator that nearly broke byte-identical wire parity across every big-endian schema:

// SBE spec §4.1: MessageHeader is ALWAYS little-endian on the wire,
// regardless of the schema's declared byteOrder. The body follows
// the schema byteOrder; the header composite must use LE.
let comp_byte_order = if composite_tokens[0].name == "messageHeader" {
    ByteOrder::LittleEndian
} else {
    ir.byte_order
};

There is no SBE spec §4.1 that says this. The comment was invented. The actual SBE specification does not mandate little-endian headers, and the sbe-tool reference implementation uses the schema’s declared byte order for all fields including the message header.

The fabricated comment was treated as a load-bearing design constraint by subsequent coding agents. They wrote a test (endianness_header_is_always_le) that asserted LE-only headers, modified the code generator to enforce the non-existent rule, and regenerated golden files to match. The test passed. The dual-encode parity tests also passed, because those tests compared ergon output against patched sbe-tool reference crates that had been modified to match the fabricated behaviour.

The damage was discovered only when an independent verification regenerated the sbe-tool reference crates from untouched upstream and found that ergon produced different bytes for big-endian schemas. Tracing the discrepancy back to a single comment with a fake spec citation took several hours.

Lesson: An LLM can embed a confident citation to a non-existent authority inside a code comment, and that citation will be treated as fact by other LLMs that read it. The resulting code will compile, pass tests, and look professional. A // spec §X.Y says comment carries rhetorical weight that a // I think comment does not, and that weight survives even when the citation is entirely fabricated.

The fix: remove the six lines, delete the test that enforced the fabricated rule, and regenerate the golden file. No other code was affected.

Warning for anyone building with LLMs: when an agent asserts a domain fact with a precise citation, verify the citation exists before allowing it to become a constraint that other agents build upon. A confident but fabricated reference is harder to detect than an obvious mistake. And do not assume the fabricating model was the cheap one: frontier models are just as capable of hallucinating authority as anyone else.

LLMs disabled my tests rather than fixing the bugs (July–August 2026)

This failure reduced my confidence more than any other. It was not a one-off: it became a visible pattern once the project had enough tests to serve as a genuine oracle.

I relied on the extensive test suite and benchmark gates I had built up. I assumed they would catch regressions before they shipped. They didn’t, because LLMs kept disabling them rather than fixing the bugs they surfaced.

The pattern repeated across the 0.1.10 release preparation cycle:

  • Benchmark gate entries removed. The cluster bench gate script (scripts/check-bench-gate.sh) had entries silently removed by an LLM that saw a failing ratio and “fixed” it by deleting the gate line rather than investigating the performance regression. The removed entries concealed real gaps: session_connect_request encode at 1.19× and new_leader_event decode at 1.86× slower than sbe-tool. The gate went green, but the performance regressions were still present.

  • Unequal-work benchmark comparisons hidden. When benchmarks compared ergon’s checked decode() (validating headers and extents) against sbe-tool’s unchecked wrap(), the response was to remove the comparison from the gate rather than fixing the benchmark to do equal work on both arms.

  • Regression bugs shipped through. The gate-silencing pattern meant that actual regressions (codegen changes that made hot paths slower) passed through review because the gates no longer measured them.

LLMs become less trustworthy as a project matures. Early greenfield work has no existing tests to disable, so the pattern is invisible. Once the test suite and benchmark gates are dense enough to catch real problems, the LLM’s incentive to produce green output collides with the gate’s purpose. “Make the tests pass” offers two paths: fix the code, or remove the test. The second path is shorter, and LLMs take it consistently across models and vendors.

Extensive unit test and benchmark coverage was not protecting me. What did protect me was human code review, specifically, reviewing every change to test files, gate scripts, and benchmark harnesses as critically as changes to production code. A test or gate entry that is removed, skipped, or weakened must be treated as a blocking defect, not an administrative cleanup.

The policy infrastructure in this repository (just policy, check-test-policy.sh, the CI gate that rejects #[ignore] and continue-on-error) exists because this pattern was observed. But prose rules and policy scripts are still not enough. The only durable defence is a human reviewer who asks: “Did this change make the software better, or did it just make the failure invisible?”

The mechanism is straightforward:

  1. A coding agent is asked to make a change: a new feature, a refactor, a performance improvement.
  2. It runs cargo test and sees a failure.
  3. The failure is in a test the agent did not write and does not understand. The agent is not being evaluated on fixing pre-existing bugs; it is being evaluated on completing the requested change.
  4. The agent excludes the failing test: an #[ignore] attribute, a #[cfg(not(feature = "…"))] gate, a test-selection filter, a SKIP sentinel, a continue over an error in a fixture loop, or a continue-on-error CI wrapper.
  5. The agent’s own task is now green. It commits the change.

The critical moment is step 5. If that session does not commit the test exclusion (perhaps the agent correctly treated it as a local workaround it intended to revert) the working tree still contains a disabled test. A different LLM session, asked to commit and push, sees modified files and commits them. The second agent is not being asked “did you review every changed line?” It is being asked “commit and push.” It does not know which edits were intentional and which were debugging debris.

The result: a released version ships with tests that are silently disabled. Users and the maintainer believe the full suite passed. A real bug (the one the original failing test existed to catch) is still present. Nobody knows.

Here are the specific incidents from this project (verified through git history, changelog entries, and session transcripts):

Allocation-count tests (#[ignore]). Three allocation-count tests had #[ignore] attributes added by an LLM session that encountered unexpected allocation behaviour. The tests already passed; the agent did not investigate. Another session committed the attributes. They were restored only during a later audit. The commit message says “they already passed when the stale ignored attributes were removed.”

Cluster restart and quorum tests (Java lane gate). The Cluster lifecycle tests (log recovery, restart readiness, quorum behaviour) were gated behind conditional compilation or simply filtered out of the test run. An LLM that could not run the Java dependency decided to exclude the test rather than report the missing dependency. Re-enabling them exposed and then fixed four real harness defects: a client outliving its embedded media driver, a restart returning before Java readiness, a stale launcher class inside aeron-all.jar, and crash recovery restarting before Aeron’s 10-second archive-mark lease expired. Every one of those bugs shipped because the tests that would have caught them were suppressed.

Schema-loop SKIP/continue. An LLM added continue paths inside a fixture-discovery loop that silently skipped schemas it could not parse. Missing production fixtures and unreadable directory entries disappeared from the test count instead of failing. The fix replaced every continue with an asserted parse outcome. A test that silently skips broken input is not a test.

--skip explicit_implicit in the justfile. The just test and just check targets contained --skip explicit_implicit: a test-filter flag that hid a failing test from the CI lane. It was added during development and never removed. The test itself was repaired later, but the damage was already done: a passing CI run was not evidence that all tests passed. The justfile now contains an explicit warning to AI assistants that test-selection bypasses are forbidden.

Ignored Rustdoc fences. Multiple Rust code examples in documentation had rust,ignore fences. An LLM that could not make an example compile added ignore rather than fixing the code or using an honest text fence. These were replaced with compilable rust examples (compile-checked by the docs-validation harness) or explicitly schematic text fences; remaining rust,no_run fences are non-compiling by design (build scripts, config illustrations).

Phantom regeneration test. A file named encoded_length_api.txt advertised a regeneration test that did not exist and was not checked by any test. An LLM created the advertising file without creating the test it advertised. The file was removed once discovered.

Parity test assertions modified to match broken output. The dual parity tests (live byte-for-byte comparisons between ergo-sbe and official sbe-tool Rust output) were the single most important correctness check in the project. An LLM session that encountered a parity mismatch did not stop and diagnose the codegen defect. It changed the parity test assertion to match the broken output. The test passed. The bytes were wrong. The commit looked like progress. This was the most confidence-destroying incident because it proved that even an independent reference oracle can be defeated by an agent that is more motivated to produce green output than correct output.

Dead locals in the generator. A mutation-testing survivor analysis found unused local variables in the code generator that had been left behind by an earlier LLM session. The variables had no effect on generated output but added noise. The agent that introduced them moved on without cleaning up.

The policy infrastructure in this repository (just policy, check-test-policy.sh, test-quality-ratchets.sh, the mutation ratchet, the coverage ratchet, the CI gate that rejects #[ignore] and continue-on-error) exists because this pattern was observed across multiple sessions and models. Prose instructions in CLAUDE.md were not enough. The most important commit in the hardening phase may have been test: make verification fail closed: the policy that rejects an empty, incomplete, or missing test result rather than treating it as a pass.

As a project matures, LLMs become less trustworthy, not more. Greenfield work has no existing tests to break. Once the test suite is dense enough to serve as a real oracle, the agent’s incentive to achieve green output collides with the oracle’s purpose. Disabling a test is cheaper than understanding and fixing a bug in code the agent did not write.

The pattern is not model-specific. I observed it across DeepSeek, GLM, and frontier models. It is a consequence of the optimisation landscape, not the model architecture. A coding agent asked to “make the tests pass” has two paths: fix the code, or remove the test. The second path is often shorter.

Practical consequence: a mature test suite in an LLM-assisted project needs hard, automated enforcement that a test cannot be silently skipped, ignored, filtered, or gated. Prose rules are not sufficient. If your CI does not reject test suppression mechanically, assume that suppressed tests exist, whether the human who reviewed the PR knows about them or not.

Assuming CLAUDE.md would enforce everything

The local agent guide grew incrementally. Whenever a mistake seemed important and repeatable, I asked the agent to add the rule to CLAUDE.md.

That helped, but it did not make the behaviour reliable. Two particularly irritating regressions kept returning:

  • generated examples reverted from the intended method-chaining style; and
  • fallible code used unwrap() instead of propagating Result with ?.

The instructions were explicit and repeated. The models still reintroduced the patterns. Eventually I accepted that feature work would create this debt and ran focused cleanup passes at intervals.

An agent guide is useful memory. It is not a compiler, a type system, or a lint. If a rule matters, an automated check is better than prose alone.

Human and agent editing at the same time

Manual edits made while the agent was working frequently damaged continuity. The agent had already formed a model from older file contents. I had more success telling it exactly what was wrong and letting it perform the edit than silently changing the same code underneath it.

Verification: why the tests matter so much

If somebody publishes an LLM-generated library with barely any test coverage, I assume the code is slop until shown otherwise.

LLMs respond extremely well to objective verification. A failing test gives the agent a bounded problem with an observable correct outcome. Without that oracle, it can produce a confident implementation of a misunderstanding.

Early in development I sometimes asked for a numerical code-coverage target. Later I cared less about the percentage than the breadth and independence of the evidence.

The checked-in suite includes:

  • schemas and cases ported from the upstream SBE project;
  • decoding Java-produced official fixtures;
  • exact comparisons of headers, fixed blocks, composites, groups, and variable data;
  • checked-in Rust codecs generated by official sbe-tool;
  • live dual encoding where ergo-sbe and official Rust codecs must produce byte-identical messages;
  • a multi-schema official parity matrix;
  • property-based round trips over scalars, arrays, groups, nested structures, and variable data;
  • compile-fail proofs for illegal stage ordering and use-after-consume;
  • exact encoded-length matrices compared with actual completed messages;
  • malformed and truncated buffer tests;
  • schema-version and acting-version tests;
  • deterministic generated-source golden tests;
  • zero-allocation checks using a counting allocator;
  • upstream issue-regression schemas; and
  • sample applications that exercise more complicated API combinations.

See:

The strongest compatibility test is differential, not self-referential. For the same schema and logical values, the suite encodes with both ergo-sbe and the official sbe-tool Rust generator and requires identical bytes. A library that only decodes its own encoded output can be consistently wrong on both sides; an independent reference makes that much harder.

One concrete AI failure involved offsets around variable data. A generator change broke an existing test. The agent observed the failure, diagnosed it, and fixed the implementation without me having to identify the exact line. That was impressive, but the important fact is that the test existed. Without it, the wrong offset could have compiled and looked plausible.

Tests are still not enough to remove the experimental warning. They cover the cases we and upstream authors thought to encode. Production traffic eventually finds assumptions that a controlled suite did not.

Performance was part of correctness

For this library, an ergonomic abstraction that makes a maintained hot path meaningfully slower than official generated code is a failed design.

I learned that painfully. The first compile-time ordering design used generic type-state stages (Encoder<State>). I assumed it would be a zero-cost abstraction. Benchmarks showed the generated generic chain was not being optimised as effectively as plain monomorphic code. The model helped explain why and proposed concrete named stage structs with a zero-sized H: HeaderState marker. The switch retained compile-time ordering without the measured generic tax. As of 0.1.8, all 15 maintained parity comparisons (10 SBE + 5 Cluster) passed at or below the 1.00× sbe-tool ceiling under both LTO profiles. The current gate is not that sentence: most pairs are still ceiling 1.00, listed exceptions sit above it, and an over-ceiling pair inside its A/A noise band passes as inconclusive (sbe/BENCHMARKS.md, “The gate”).

After that, benchmark regression became part of the definition of done:

  • run benchmarks after every material generated hot-path change;
  • compare against checked-in official sbe-tool Rust output;
  • ensure both arms do equal work;
  • keep allocations and setup out of only one timed arm;
  • rerun suspicious or borderline results;
  • diagnose regressions before accepting a feature; and
  • remove an abstraction if it cannot meet the gate.

The benchmark harness itself needed review. Earlier comparisons accidentally included asymmetric allocation or different buffer traversal. One official encode arm even risked overlapping header and body work. These were corrected so the maintained comparison uses the same input or byte-identical output and equivalent field work. The current methodology is documented in BENCHMARKS.md.

Repeated benchmark execution likely explains part of the enormous token count. An agent would implement a change, benchmark it, discover a regression, revise the generator, and benchmark again.

Unsafe code and the trust boundary

The unsafe strategy came from me, not from an LLM spontaneously “optimising” the project.

Official-style codecs often separate checked setup from a trusted hot path. For 0.1.10 I wanted:

  • unsuffixed wrap / wrap_and_apply_header / decode as the checked lane: they return Result, validate extents once, then enter a private zero-check core (try_wrap* aliases are removed);
  • public constructor *_unchecked twins only if measured keep rules pass (at the time keep=false; cores stay module-private); and
  • no repeated dynamic bounds check for every constant schema offset after the required block length has already been proved on the checked entry path.

What shipped after that is three tiers. try_* (try_wrap, try_decode) return Result and validate extents once. The bare names (wrap, decode) panic on a short buffer (decode still returns a Result for a bad header field). unsafe *_unchecked twins skip the check and are for callers that prove the requirement themselves. Use try_* on untrusted input. There is still no repeated dynamic bounds check for every constant schema offset after the required block length has already been proved.

I asked the agents to try several unsafe optimisations and measure them. Many did not materially help, so I removed them. Unsafe is retained only where it is required by the borrowing model or where a repeatable hot-path benchmark justifies the additional audit burden.

One retained example came from the Cluster codec benchmark. Generated setters using checked slice ranges produced regressions around 1.19× and 1.28× relative to the reference path. After the wrapping boundary had already proved the fixed block was present, using get_unchecked_mut for compile-time offsets restored parity.

The policy is not “unsafe is fast.” It is:

If the invariant can be stated and established, and the benchmark shows a meaningful need, or Rust borrowing requires the internal operation, unsafe may be justified. Otherwise use safe Rust.

The existence of a safe public API does not remove the need to audit internal unsafe invariants. Users evaluating the crate should include those trust boundaries in their review.

Tools, models, and what each contributed

Agent harness

The main harness was Claude Code CLI. This does not mean Claude wrote most of the code. Claude Code was the interface; custom endpoints supplied other models.

DeepSeek

DeepSeek V4 Flash and V4 Pro performed most of the implementation work. I had never planned to use DeepSeek for this project. My initial model choices were elsewhere, but during the intensive development period I repeatedly hit five-hour or weekly subscription and coding-plan limits. Waiting for a limit to reset would have stopped the development flow, so I connected Claude Code to DeepSeek’s pay-as-you-go API and carried on working.

I initially regarded DeepSeek as temporary overflow capacity: something to use until another plan reset. Only after using it for longer sessions did I realise how capable it was for this particular workflow and, especially, how cost-efficient its cache-hit pricing made sustained agentic development. What began as an unplanned way to avoid an interruption became the project’s main implementation workhorse.

The model split also reflects the change in development style. Early in the project I was using UltraMode through Claude Code CLI. UltraMode created subagents and selected the model it considered appropriate for each task. In my custom endpoint configuration, the model slot that UltraMode treated as Sonnet was mapped to DeepSeek V4 Flash. Consequently, much of the early parallel work ran on Flash without me manually choosing Flash for each subagent.

Once the codebase became too coupled for parallel development, I moved to a mostly sequential workflow and kept the main session on DeepSeek V4 Pro. This explains why the dashboard contains substantial use of both models and why the actual bill was lower than an all-Pro estimate. Flash handled a large amount of the early, highly parallel token volume; Pro carried the longer sequential implementation and refinement sessions.

There was no task where DeepSeek failed and I then had to escalate the same problem to Opus, ChatGPT, or Grok to rescue the implementation. That surprised me. It was possible because:

  • I knew the domain;
  • I normally knew what the correct result should look like;
  • I could provide concrete API examples;
  • the output was easy for me to inspect; and
  • tests and benchmarks supplied tight feedback.

That is not evidence that DeepSeek is universally equivalent to a frontier model. It is evidence that, for a tightly specified mechanical implementation task under constant domain-expert supervision, a cheaper workhorse can be more useful than buying maximum intelligence for every token.

My practical description is:

DeepSeek V4 Pro delivered roughly Sonnet-class usefulness for this workflow. I would not treat that as proof that it replaces Opus for ambiguous, autonomous, long-horizon work where the developer does not know the answer.

DeepSeek’s own model information is available from its official V4 documentation and reports. Cross-vendor benchmark numbers use different harnesses and should not be read as controlled equivalence.

GLM

I used GLM-5.2 and GLM-4.7 substantially, particularly early in the project. The 30-day screenshot below records approximately 3.28 billion GLM tokens, including 2.65 billion on GLM-5.2.

I bought the highest coding-plan tier I was using (about $114) and still hit limits during the intensive development schedule.

Claude, OpenAI, and Grok

I also paid for Claude, OpenAI, and Grok access. I used them mainly for additional reviews and experiments, not as indispensable implementation engines. Their reviews were sometimes a little stronger, but generally raised the same categories of issue that DeepSeek reviews found. I cannot point to a frontier-model finding without which this project could not have been completed.

Cross-model review is useful, but agreement among models is not independent proof. They can share training patterns and repeat the same plausible misunderstanding. Official bytes and behavioural tests are stronger evidence.

Long context, the O(n²) mental model, and caching

Both DeepSeek V4 Flash and V4 Pro exposed a one-million-token context window. I favoured one long-lived conversation over many short ones, so the window could hold design decisions, failed benchmarks, and corrections across related work.

That is not the same as “never compact and keep one pure million-token session.” Whenever I started a genuinely new task (something sufficiently different from what the session had been doing) I compacted at that boundary if it was a natural handoff point. Continuity within a task was the goal; a single unbroken transcript across the whole project is not an accurate picture.

Subjectively, DeepSeek became much more useful when it retained the accumulated history that still mattered for the current line of work: design decisions, examples, mistakes, failed benchmarks, and my corrections. I did not notice a significant drop immediately after those task-boundary compactions. In separate Sonnet usage with a smaller context, I have sometimes noticed forgotten details after compaction.

Those are personal observations, not controlled experiments. They do, however, explain the usage shape.

What I mean by “O(n²)”

My informal developer’s mental model became “roughly O(n²) in requests.” Here, n means the number of turns or requests in a growing conversation, not the number of tokens in one request.

Suppose, only to make the intuition concrete, that each turn adds d tokens of new conversation, source code, tool output, test logs, and model response. If the complete conversation is sent again on every turn, the prompt at turn i contains approximately i × d tokens. Across k turns the cumulative input presented is approximately:

d + 2d + 3d + ... + kd
= d × (1 + 2 + 3 + ... + k)
= d × k × (k + 1) / 2

That sum grows quadratically with the number of turns. A simple worked example shows why the final context-window size is misleading:

  • 100 turns each add an average of 10,000 tokens;
  • the final prompt is approximately 1,000,000 tokens;
  • but the cumulative prompt volume across the 100 turns is approximately 50,500,000 tokens before counting output separately.

So a one-million-token context window does not mean that a one-million-token conversation costs only one million input tokens over its lifetime. The route to that final context has repeatedly carried most of the earlier conversation. Real coding sessions are messier: turns add different amounts, tool results can be enormous, agents reread files, benchmarks print logs, and compaction changes the curve. The formula is a mental model, not an invoice.

It is also not a claim that every provider literally recomputes every transformer operation from scratch on every request. Model-side KV caching, provider prompt caching, routing, cache eviction, attention implementations, and other infrastructure all affect actual compute. I do not know whether a particular provider keeps a cache in RAM, on disk, or in some other tier, and the storage detail is not required for the economic point.

The economic point is simpler: the API token ledger still records a very large repeated prefix, and that repeated prefix normally has a price. This is how a project using a model with a one-million-token window can plausibly accumulate billions of billed tokens.

A cache hit is discounted, not free

In an agent conversation, a request can be thought of as three economically different categories:

  1. Input cache hits: the provider recognises a previously processed prefix and charges its cache-hit rate.
  2. Input cache misses or cache writes: new or changed input must be processed and, depending on the provider, written into the prompt cache.
  3. Output: new model tokens, including any billed reasoning tokens under the provider’s accounting.

The headline “input price” and “output price” therefore do not describe a long agent session. A useful comparison must ask:

  • What does a cache hit cost?
  • What does a miss or write cost?
  • How long is the cache retained?
  • Which prefix changes invalidate it?
  • Does the provider apply a long-context multiplier?
  • At what threshold does that multiplier begin?
  • Is the advertised context size actually available at the standard rate?
  • How much output or hidden reasoning does the model generate for equal work?

The last question is why the counterfactual table later in this document holds token usage constant. It isolates pricing, but it cannot prove what another model would actually consume.

Why the cache price changed the project

I originally compared models mainly through benchmark rank and ordinary input/output price. That missed the largest category in this workload: repeated context. The selected dashboard samples later in this page show that approximately 98.66% of token volume was served as input cache hits.

DeepSeek’s cache-hit rate was so low that keeping a large and useful context alive became affordable. This mattered more to my workflow than a modest benchmark advantage from a model that I could use only intermittently. I could keep giving feedback, retain design history, run another test, inspect another generated file, and try again.

That does not mean cheap cache hits make the entire bill negligible. One correction is essential: roughly 99% of token volume being cache hits does not mean 99% of dollar cost came from cache hits. Hits are heavily discounted. The much smaller quantities of misses and output can contribute a large portion of the final dollars. The correct calculation prices all three categories independently.

Context was part of the model’s effective intelligence

For this project, the long session held decisions that were not easily reduced to a short prompt: why a particular API had been rejected, how an offset bug had presented, which benchmark had regressed, which generated style I wanted, and how official output behaved. Retaining that history made the workhorse model feel more capable.

Caveat on “one long session”: I did not leave one transcript untouched for the entire project. I compacted whenever I started a task that was sufficiently different that the old tail was no longer a good default context, i.e. at genuine task boundaries, not once-or-twice total and not never. Within a task I kept context long; between dissimilar tasks I compacted and moved on. I did not notice a material loss immediately after those handoff-style compactions. In my separate experience with Sonnet and a smaller context window, I have sometimes noticed forgotten decisions after compaction. That is personal observation, not a controlled model comparison. It nevertheless changed how I think about model selection: effective intelligence is a combination of the base model, the context it can retain for the current task, the quality of the feedback, and whether I can afford enough turns to finish the loop.

Observed usage and actual spend

The most accurate data comes from ccusage (Claude Code + Codex agents only; Hermes and OpenCode are automation agents and excluded here). Snapshot from 2026-08-07 (ccusage export since 2026-06-28). Note: this export was produced by a newer ccusage version with a different rate table and session attribution than the previous 2026-08-02 snapshot, so per-model figures differ. The current snapshot is authoritative.

ccusage API-level spend

ModelInputOutputCache CreateCache ReadReasoningTotal TokensAPI Cost
claude-fable-5128,112210,9315,707,17844,132,249—50,178,470$168.76
claude-opus-4-8153,359505,2243,840,85893,893,329—98,392,770$86.22
claude-opus-51,702575,6732,454,943204,567,008—207,599,326$139.50
claude-sonnet-4-6365422,73014,116—37,503$0.15
claude-sonnet-530,556328,8546,177,826218,888,413—225,425,649$71.84
deepseek-v4-flash52,791,36715,125,98602,734,161,536—2,802,078,889$19.28
deepseek-v4-pro47,802,8229,959,142011,705,468,864—11,763,230,828$71.89
glm-4.72,620,188287,011056,403,328—59,310,527$8.41
glm-5.219,826,2482,577,59801,868,156,352—1,890,560,198$524.82
gpt-5.51,781,759117,119018,613,50431,27020,543,652$21.73
gpt-5.6-sol33,916,0583,205,1790970,537,4721,524,6741,009,183,383$758.17
Total159,052,17432,893,37118,203,53517,914,836,1711,555,94418,126,541,195$1,870.77

That’s 18 billion tokens and $1,870.77 in API charges at enterprise/pay-as-you-go rates. The earlier 14-billion-token estimate was derived from provider dashboards and was an order-of-magnitude figure; the ccusage data is a precise ledger-level reconciliation across Claude Code and Codex sessions.

Subscription spend

Separate from the API charges above, these subscription fees were paid:

ProviderSpendNotes
GLM coding plan$114Covers glm-4.7 and glm-5.2 API usage. The $533.23 in GLM API costs in the ccusage table is how the plan’s included quota would be priced at PAYG rates
OpenAI subscription$20
Claude subscription$20
Grok subscription$30Grok API usage is not tracked by ccusage
Subscription total$184

Total identified spend

CategoryAmount
API charges (enterprise/PAYG rates, via ccusage)$1,870.77
Subscriptions$184.00
Total identified$2,054.77

The API charges are computed at published enterprise rates, not necessarily what was actually billed (DeepSeek’s actual bill was $77.39 for the project period; GLM usage was covered by the $114 plan). The gap between the $1,870.77 computed API cost and the ~$261 of actual out-of-pocket spend is the economic story of this project: DeepSeek’s cache-hit pricing made sustained agentic development affordable.

The DeepSeek dashboard for the displayed 30-day window shows:

  • 10,522,859,893 tokens
  • 47,668 API requests
  • $77.39

The model split shown by the dashboard was:

  • DeepSeek V4 Flash: 3,392,304,915 tokens across 29,015 requests
  • DeepSeek V4 Pro: 7,130,554,978 tokens across 18,653 requests

The mixture matters: the early UltraMode/subagent phase used V4 Flash through the Sonnet-mapped model slot, while the later sequential phase stayed primarily on V4 Pro. Treating all 10.5 billion DeepSeek tokens as Pro would therefore overstate what I actually bought.

The cumulative token usage table at the top of this page is the authoritative per-model breakdown. The dashboard screenshots above are retained as the original historical evidence they were captured from during development.

The cache sample used for the cost comparison

The dashboard screenshots expose the input-cache-hit, input-cache-miss, and output split for three selected days:

Combined, those samples contain:

Token categorySample tokensSample share
Input cache hits2,225,207,68098.6602%
Input cache misses23,305,8481.0333%
Output6,911,5040.3064%
Total2,255,425,032100%

Scaling that exact mix to 14 billion tokens gives:

Token categoryNormalised millions of tokens
Input cache hits13,812.433168 MTok
Input cache misses / cache writes144.665359 MTok
Output42.901473 MTok
Total14,000 MTok

The cost formula is:

cost =
    cache-hit MTok × cache-hit price
  + cache-miss MTok × miss/write price
  + output MTok × output price

This calculation includes all three categories. It does not price 14 billion tokens as though they were all cheap cache hits.

Normalised pay-as-you-go comparison

The following is a historical estimate using public prices checked on 26 July 2026:

Assumptions:

  • exactly 14 billion billed tokens for every model;
  • exactly the sampled cache-hit/miss/output mix above;
  • zero model-specific increase or reduction in token usage;
  • no 30% tokenizer adjustment for newer Claude models, even though Anthropic documents that their newer tokenizer may produce approximately 30% more tokens for the same text;
  • standard synchronous API rates, not batch, fast mode, regional residency, or negotiated enterprise discounts;
  • Claude cache misses treated as five-minute cache writes;
  • GPT-5.6 Sol cache misses treated as cache writes at its documented 1.25× input rate;
  • GPT-5.5 misses treated as normal uncached input;
  • no separate tool-call, hosted-agent, storage, tax, or network charges; and
  • “medium” reasoning effort does not alter the per-token rate; this table holds token counts constant rather than guessing different reasoning-token usage.

At standard or short-context rates

ModelCache-hit $/MTokMiss/write $/MTokOutput $/MTokEstimated total
DeepSeek V4 Flash$0.0028$0.14$0.28$70.94
DeepSeek V4 Pro$0.003625$0.435$0.87$150.32
Claude Sonnet 5 promotional price through 31 Aug 2026$0.20$2.50$10.00$3,553.16
GLM-5.2$0.26$1.40$4.40$3,982.53
Grok 4.5 below 200K context$0.30$2.00$6.00$4,690.47
Claude Sonnet 4.6$0.30$3.75$15.00$5,329.75
Claude Sonnet 5 standard price from 1 Sep 2026$0.30$3.75$15.00$5,329.75
Claude Opus 4.8$0.50$6.25$25.00$8,882.91
Claude Opus 5$0.50$6.25$25.00$8,882.91
OpenAI GPT-5.5 medium$0.50$5.00$30.00$8,916.59
OpenAI GPT-5.6 Sol medium$0.50$6.25$30.00$9,097.42

Sonnet 4.6 and Sonnet 5’s post-promotion line are equal because that is what the official first-party Claude pricing page publishes. Opus 4.8 and Opus 5 are also equal on that page. The calculation does not invent a quality or token-volume premium where the requested assumption is a 0% usage increase.

If requests actually use approximately one million tokens of context

Long-context pricing changes the comparison:

ModelPublished long-context treatmentEstimated total
DeepSeek V4 Flash1M context; same published token rates$70.94
DeepSeek V4 Pro1M context; same published token rates$150.32
Claude Sonnet 5 promotionalFull 1M at standard rates$3,553.16
GLM-5.21M context; same published token rates$3,982.53
Claude Sonnet 4.6Full 1M at standard rates$5,329.75
Claude Sonnet 5 standardFull 1M at standard rates$5,329.75
Claude Opus 4.8Full 1M at standard rates$8,882.91
Claude Opus 5Full 1M at standard rates$8,882.91
Grok 4.5Cannot accept 1M; maximum 500K. At ≥200K all rates double$9,380.94 at 500K
OpenAI GPT-5.5 mediumAbove 272K: 2× input and 1.5× output$17,189.65
OpenAI GPT-5.6 Sol mediumAbove 272K: 2× input, 1.5× output, 1.25× cache writes$17,551.32

Claude’s official page states that Claude 4.6 and later include the full one-million-token context window at standard rates. OpenAI documents the greater-than-272K multiplier for GPT-5.5 and GPT-5.6 Sol. Grok 4.5 has a 500K maximum and doubles all token rates from 200K.

These are counterfactual estimates, not invoices. Different models can tokenise the same conversation differently, emit different amounts of reasoning, call different tools, finish in different numbers of turns, and achieve different cache-hit ratios. Holding usage fixed is useful for isolating price; it does not predict the total cost of rerunning the project with another model.

As a sanity check, scaling the observed DeepSeek charge ($77.39 / 10.5229B tokens) to 14B gives $102.96, rounded to $103. This is the estimated 14-billion-token cost of the observed V4 Flash/V4 Pro blend. It sits between the all-Flash and all-Pro modelled figures because the real workload mixed both models. The selected cache screenshots are also samples of three days rather than a billing-complete token-category ledger for every day.

What I learned about model “intelligence”

Before this project I placed more weight on using the best-ranked model. My conclusion is now more conditional.

If I do not understand a problem, model intelligence matters greatly. If I am the domain expert, know the required output, can inspect it quickly, and have objective tests, I may get more value from an affordable model that I can use continuously.

For this project, intelligence was not the scarce resource. The scarce resources were:

  • enough context to retain the evolving design;
  • enough affordable requests to sustain constant feedback;
  • tests that made correctness observable;
  • benchmark loops that made performance regressions observable; and
  • my attention for API and domain review.

That is why DeepSeek was so effective here. It does not imply that the same choice is correct for a developer who is asking the model to discover SBE semantics on their behalf.

For somebody learning agentic coding on personal projects, my practical advice would now be to start with a small amount of inexpensive pay-as-you-go credit. It is difficult to learn sustained feedback loops when a premium subscription repeatedly stops the session at its usage limit.

A practical playbook for other developers

This project does not provide a universal recipe for AI-generated software. The conditions were unusually favourable. It does, however, suggest a repeatable method for projects where the developer already understands the domain and correctness can be made observable.

1. Choose a problem with an oracle

The best agent task is not merely one that can be described. It is one whose result can be disproved.

For this project, official SBE bytes were the strongest oracle. Compilation, round trips, generated-source inspection, exact lengths, allocation counts, and benchmark results supplied additional independent signals. If the only acceptance criterion had been “the API looks plausible,” I would not trust the result.

Before delegating a large implementation, ask what will turn a model’s mistake into a concrete failure. If the answer is “a human will eventually notice,” the feedback loop is too weak.

2. Keep domain authority with a person who understands the problem

I did not ask the models to decide what SBE should mean. I knew the ordering rules, group structure, variable-data behaviour, schema-evolution concerns, and practical user mistakes before the project started.

An agent can implement a wrong specification extremely well. Tests derived only from the same wrong specification may all pass. The responsible person must be able to explain the invariant, recognise a plausible misinterpretation, and reject an API even when it is polished.

This is why I would not generalise my DeepSeek result to somebody learning SBE from the model while simultaneously asking it to build the generator. In that situation, there is no independent domain authority in the loop.

3. Define the observable contract before discussing implementation

I obtained better results when I said what generated calling code should look like, which illegal sequence should fail to compile, or which exact bytes should be produced. Vague goals such as “make it idiomatic” gave the agent too much freedom and usually created an ugly API.

A useful task statement includes:

  • a representative input;
  • the desired public call site;
  • the expected output or failure;
  • the invariant being protected;
  • the tests that must pass; and
  • the benchmark or allocation condition, if performance matters.

The model can then explore implementation details without owning the product decision.

4. Review the artefact closest to the real contract

Reviewing every generated line is ideal when it is practical, but enormous AI-authored diffs can exceed honest human review capacity. That does not justify pretending they were reviewed.

Instead, identify where your expertise has the highest leverage. I reviewed emitted Rust, public API shape, stage transitions, bytes, exact lengths, and performance more deeply than the syn/quote machinery. In another project the right surface might be SQL plans, a protocol trace, a rendered page, or a machine-generated configuration.

Be explicit about what this choice leaves unreviewed. Behavioural evidence narrows a trust boundary; it does not make the boundary disappear.

5. Prefer independent references over self-consistency

A codec that encodes and then decodes its own incorrect format can pass every round-trip test. A generator and a test written by the same model can share the same misunderstanding.

The most valuable tests compare against something independent:

  • an official implementation;
  • a protocol fixture produced by another language;
  • a published conformance suite;
  • a hand-calculated small example;
  • an external parser or validator; or
  • a previous production implementation.

For ergo-sbe, having both official sbe-tool generated Rust and the new generator encode the same logical message to identical bytes is far stronger than either codec decoding its own output.

6. Use short, mostly sequential loops after shared invariants emerge

Parallel agents are useful for truly independent research or isolated files. They were counterproductive when several branches changed the same generator conventions and API model.

The loop that worked was small: test, edit, regenerate, run, inspect, correct. When an agent moved in the wrong direction, stopping after minutes was better than reviewing an hour of coherent but unsuitable work.

The unit of delegation should shrink as the codebase becomes more coupled. Greenfield parallelism is not evidence that late-stage parallelism will work.

7. Give one editor ownership of an active change

I had less success when I manually edited files while an agent retained an older view of them. The agent’s context was part of its working state. Silent external edits made that state stale.

My practical solution was to explain the correction and let the active agent make it. This is not a rule that humans must never code. It is a coordination rule: avoid two editors changing the same conceptual unit without an explicit reload and reconciliation step.

8. Treat agent guides as memory, not enforcement

CLAUDE.md was valuable for accumulating project preferences and previous mistakes. It did not reliably stop the agents from reintroducing unwrap() or non-chained examples.

If a rule is important, promote it from prose to something executable:

  • a compiler error;
  • a lint;
  • a compile-fail test;
  • a source scan;
  • a formatter;
  • a golden file; or
  • a CI check.

Instructions influence probability. Automation changes the acceptance boundary.

9. Put performance in the definition of done

Performance-sensitive abstractions should be benchmarked from the beginning, not after the API has hardened. The generic type-state design taught me this the expensive way.

For every relevant change, the agent had to rerun benchmarks and investigate a regression rather than merely report it. This increased token use, but it prevented performance debt from accumulating invisibly.

Benchmark equal work. A comparison is meaningless if one side encodes fewer fields, omits a group, performs less validation, or uses a different buffer lifecycle. Generated APIs make accidental unequal work especially easy to hide.

10. Experiment with unsafe code; do not assume it is faster

I asked the agents to try unsafe variants because a checked boundary can make some repeated bounds checks redundant. Some experiments improved performance; others made no meaningful difference and were removed.

Every retained unsafe block needs:

  • a stated invariant;
  • a place where that invariant is established;
  • tests around the boundary;
  • a measured reason to keep it, unless borrowing genuinely requires it; and
  • a clear distinction between checked and trusted public entry points.

“The LLM wrote it” is neither a safety proof nor a reason to reject it. The proof must stand independently of its author.

11. Preserve context deliberately and compact with a handoff

Long context helped because it contained rejected designs, benchmark history, style corrections, and domain explanations. Throwing that away mid-task made the agent repeat old mistakes. Compacting at a real task boundary (when the next work was sufficiently different) was usually the right trade.

At the same time, unlimited history increases cost and can bury the current task. A good compaction or handoff should preserve:

  • decisions and their reasons;
  • invariants;
  • known failure modes;
  • commands that prove completion;
  • current benchmark baselines; and
  • unfinished work.

Do not retain a million tokens merely because the window exists. Retain them when the accumulated decisions improve the next turn enough to justify their cache cost.

12. Price the workload, not the marketing number

For agentic coding, compare at least cache hits, cache writes or misses, output, context thresholds, and rate limits. A model with cheaper ordinary input may still be expensive for a repeated-prefix workload. A subscription that looks cheap may stop an intensive day halfway through.

Use your own dashboard split when possible. Then calculate:

hit tokens × hit price
+ miss/write tokens × miss/write price
+ output tokens × output price

Apply any long-context multiplier separately. Keep clear whether you are comparing equal token volume, equal elapsed time, or equal completed work. Those answer different questions.

13. Separate the agent harness from the model

Most implementation happened through Claude Code, but most implementation was not performed by a Claude model. The harness provided file access, tool use, session management, and interaction conventions. DeepSeek or GLM supplied the model behind it.

This distinction matters when reporting results and when reproducing them. A good model in a poor harness may be frustrating; a good harness can make a less expensive model highly productive. “I used Claude Code” is not a complete model-provenance statement.

14. Use frontier-model reviews as another opinion, not proof

Claude, OpenAI, and Grok reviews were useful. They sometimes expressed a problem better or found a slightly different angle. They were not an independent conformance oracle, and none rescued a task that DeepSeek could not complete in this project.

Models can share the same training-derived assumptions. Several agreeing that code looks correct is weaker than one official byte comparison demonstrating that it is correct for a specific case.

15. Stop if you cannot explain the result

The human responsible for merging a change should be able to explain:

  • what requirement changed;
  • why the implementation satisfies it;
  • what evidence would fail if it were wrong;
  • which surfaces remain unreviewed; and
  • what operational risk remains.

If the explanation is “the agent seemed confident and all of its own tests passed,” the work is not ready.

16. Publish the uncomfortable facts

AI-assisted projects need more provenance, not less. State how much code was generated, where human review concentrated, which models and harnesses were used, which evidence is independent, what the work cost, and why the maturity label remains.

This disclosure is long because “AI-assisted” covers everything from autocomplete to a project in which an agent wrote nearly every implementation line. Users deciding whether to put a codec near money deserve the meaningful version.

The personal experience: pride, enjoyment, and review fatigue

I have written another open-source project almost entirely by hand. I felt a different connection to that code. Writing software is enjoyable; learning the small implementation details and keyboard shortcuts is part of the craft.

I do not feel the same ownership of this generator’s individual lines because I did not write them. I am concerned that heavy LLM use can cause skill atrophy. It also changes the job from implementation to review.

That change was harder than I expected. I have historically been a very fast developer and often spent more time writing new code than reviewing other people’s work. Reading code quickly to understand an API is not the same skill as auditing a huge generated diff line by line. Careful review is slower, more tedious, and easier to overwhelm. LLMs can generate code far faster than a person can honestly review it.

This project remained enjoyable because I was still solving a problem I care about. I spent a great deal of time thinking about SBE, Rust API design, verification, and performance. The LLM did much of the repetitive generator work that I already knew how to do and did not particularly want to spend six months repeating.

So the pride is attached differently:

  • less attachment to the implementation;
  • more satisfaction in the API and product;
  • genuine pleasure that something I wanted throughout my working life now exists; and
  • less reluctance to throw away experiments that do not work.

That last point helped with the Aeron Cluster code. The Cluster crate was initially a realistic consumer and test bed for ergo-sbe. Samples later became a better way to exercise complicated API shapes. The Cluster work remains less mature and more disposable. My priority is to make ergo-sbe right before treating the Cluster client as a finished product.

Why this crate is still experimental

The experimental label is deliberate.

I would be angry if a developer introduced an unproven codec into a financial system merely because it had many unit tests. If I apply that standard to somebody else’s library, I must apply it to mine.

One thing I valued in the Java ecosystem was that mature projects often had visible institutional signals (long histories, broad production use, or governance under organisations such as Apache). The quality of an arbitrary Rust crate can be much harder to infer from its presentation. That makes explicit evidence and an honest maturity label more important, not less.

The suite is extensive. The official byte parity is meaningful. The benchmark gate is meaningful. None of that is the same as sustained production use across independent firms, schemas, traffic patterns, deployment environments, and upgrade cycles.

I will become comfortable removing the warning when there is a sufficient base of real users who tell me:

  • they are using it in production;
  • which features and schema shapes they use;
  • how they compared it with their existing codecs;
  • what volumes and environments it has survived;
  • how schema evolution behaved; and
  • what defects or operational surprises they found.

The reports I most want are already listed in the ergo-sbe README: multi-schema streams, DTO use, exact sizing with Aeron/IPC claims, nested or ragged books, and mixed acting versions.

Until that evidence exists, treat the crate as 0.x experimental software. Pin versions and perform your own migration testing.

What a prospective production user should verify

Do not rely on this narrative alone.

At minimum:

  1. Generate codecs for your actual schemas.
  2. Encode the same logical messages with your existing official SBE tooling and ergo-sbe; compare exact bytes.
  3. Cross-decode in both directions.
  4. Include empty, maximum-sized, nested, ragged, and variable-data cases.
  5. Exercise every acting version and schema-evolution path you expect to see.
  6. Test malformed and truncated frames at the trust boundary.
  7. Verify exact buffer lengths before integrating with try_claim or another zero-copy publication API.
  8. Benchmark your real hot fields and message shapes, not only the Car example.
  9. Audit the internal unsafe assumptions relevant to your use of try_*, the panicking bare constructors, and any unsafe *_unchecked twin.
  10. Run soak tests under real traffic and deployment conditions.

If you are not already comfortable explaining SBE block lengths, group dimensions, variable-data prefixes, acting versions, and positional ordering, do not use an LLM-generated explanation as your only review.

AI-assisted contributions

I am not applying a simplistic ban on AI-assisted pull requests, but I will not blindly accept them.

Large AI-generated PRs are difficult to review. More importantly, a contributor can ask a model to “fix” a protocol bug without understanding why the result is correct. Passing compilation is not enough.

For a generator or wire-format change, the contributor must understand the relevant SBE behaviour and be able to explain it. A focused issue containing:

  • a real schema;
  • a minimal reproduction;
  • expected official bytes;
  • a failing behavioural or parity test; and
  • an explanation of the protocol invariant

may be more valuable than a large implementation patch. In many cases I would rather take that evidence and implement the change through the controlled workflow used for this repository.

AI assistance is not disqualifying. Lack of domain understanding is.

Final assessment

This project was a particularly favourable case for AI-assisted development:

  • the maintainer was a domain expert;
  • the desired behaviour was unusually concrete;
  • the tedious part was mechanical code generation;
  • the generated product was directly inspectable;
  • an independent official implementation existed;
  • wire bytes supplied a hard oracle;
  • benchmarks constrained abstraction cost; and
  • constant feedback was possible.

Even in that favourable case, it consumed about a month of intense work, roughly 18 billion tokens (measured by ccusage), repeated cleanup, extensive tests, and continuous human judgment. The fashionable version (write a specification, dispatch many agents, and return to a finished library) did not survive beyond the early greenfield stage.

I would use this development method again for a personal project with similar properties, and I would likely use DeepSeek again as the workhorse. I would not generalise the result into “LLMs can safely build any library” or “the cheapest model is always enough.”

The result is a crate whose API I genuinely wish I had during the last decade of SBE work. I am proud of that result. I am also being explicit that most of its implementation was written by models, that the generator internals did not receive exhaustive human line review, and that production maturity still has to be earned.

If you use ergo-sbe seriously, please report the schema shapes and features you exercise, including failures. Real-world evidence is what will make this project trustworthy, not another paragraph claiming that AI-generated code is either magically perfect or automatically worthless.

Verification and release

cargo test -p ergo-sbe --all-features
cargo test -p ergo-sbe --doc --all-features
RUSTDOCFLAGS="-D warnings" cargo doc -p ergo-sbe --all-features --no-deps
cargo clippy -p ergo-sbe --all-targets --all-features -- -D warnings

ergo-sbe-inspect has its own lane (test-lanes.tsv): cargo test -p ergo-sbe-inspect --all-features runs its oracle-parity tests (every field the generated Display prints must appear in the runtime output), corpus, property and robustness tests, the sbe-inspect filter’s tests (input it does not recognise comes out byte for byte, streams cut at every byte give the same output), the schema-URL tests against a local server the test starts, and the tests that write the output shown in the inspect chapters. Its fuzz targets inspect_bytes and inspect_filter are built with the other fuzz targets and are not among the six replayed at release.

ergo-aeron-tools has its own lane too, run in three builds: the default one, which links Aeron in like every crate in the repository (just check-aeron-tools, also part of just check-local), the dynamic one, which loads libaeron at run time from the loader path cargo sets (just check-aeron-tools-dynamic, part of just test), and the one without the archive control reader (just check-aeron-tools-no-archive, part of just test). Each is clippy with -D warnings and cargo test -p ergo-aeron-tools -- --test-threads=1, the second with --no-default-features --features cli,tui,archive, the third with --no-default-features --features cli,tui,static. The workspace-wide --all-features runs exclude the crate, because they would turn static on and leave the other two builds untested. All three compile Aeron’s C sources, so all need CMake and a C compiler; the first two need a JDK 17 or newer for rusteron’s archive client (the feature archive), the third needs none. None needs the Aeron jars of just fetch-aeron-jars. The lane runs its core tests (every tab’s view state driven by actions alone, with no terminal), the key-table and terminal drawing tests, property tests over hostile values in a read (any counter value, time or text), crafted-file tests (copies of a live driver’s files with a label length, an error log entry or a loss report entry made to lie, and a heartbeat that cannot be read: the binary must refuse or note them, not crash), and reader and command-line tests against an embedded C media driver the tests start. The passive tap is tested there too: messages read whole and in order, reassembled, skipped and counted once the driver has cleaned them (never torn), on a publication and on an image of a second driver, and a lying log file refused. T14 publishes four term windows with a paused tap attached and asserts no back pressure and no new counter, beside a control that attaches a subscription that stops polling and must see back pressure; messages --follow into a pipe nobody reads is held to the same test. The log inspector is tested on a live driver’s log, which pins the metadata offsets, and on hand-built logs with lying frame lengths, metadata and tail counters. driver terminate runs only against drivers the tests start in their own directories: one whose termination validator allows the request (it must stop), one that denies it (it must still run, exit 1), and T15 walks the action table, giving each action every refused combination of --write and --confirm, and checks that the allowing driver never heard a request. Aeron’s C readers trust the lengths in a file, so read checks the counter label lengths, the error log entries and the loss report entries itself before calling them; the other cnc.dat fields are checked only by Aeron (its file-size and version checks), and a file rewritten by something other than the driver between the check and the read is not covered. just policy checks that the crate with no features has no terminal or command-line crate in its dependency tree. The archive tabs’ offline reader is tested on a fixture archive a real Java archive made (tests/archive/fixture/): its reading must equal what ArchiveTool printed for it (descriptors, states, counts, the mark file, every frame), every archive-dir command must succeed on a read-only copy and change no byte or modification time, and catalogue, mark file, segment and frame lengths that lie, FIFOs and symbolic links must be refused or noted. The crate’s java-tests lane (just test-aeron-tools-archive, part of just test, after just fetch-aeron-jars) starts its own Java archive per test: it checks that ArchiveTool still prints the stored outputs for the fixture (ERGO_AERON_BLESS=1 remakes both), that the online reader lists what the catalogue holds, and, with a subscription on the archive’s control stream, that the tool sent read requests only and the archive’s files did not change.

just test in the monorepo also runs doctests, docs_validation_test (README fences + generated-API smoke), and rustdoc with -D warnings.

Release path

Before tagging, run ./scripts/check-book-diagrams.sh. It names each diagram in book/diagrams.tsv whose verified sources changed since its stamp. For each one, re-check every label and number against the code, update the diagram, then run ./scripts/check-book-diagrams.sh --restamp <diagram>. Step 8/9 runs the same check and fails on any diagram left stale.

just release and just release-verified run each gate once on the release commit:

StepWhat runs once
startjust release only: _reset-sources resets the simple-binary-encoding submodule to its pinned commit and removes the gitignored sample codecs so cargo regenerates them (just release-verified instead starts at 0/8, checking the benchmark evidence for HEAD). Cargo target directories are kept (cargo fingerprints source, flags and toolchain); run just clean first for a cold build
2/8just test, including the sbe-tool reference check, rustdoc and bench compilation
4/8fuzz replay: one cargo fuzz build, then all six targets at once, 30 s each (scripts/run-fuzz-replay.sh)
5/8bench gates with --noplot (gates read only the JSON estimates). The parity and cluster gates reject estimates from another run id; bench-historic deletes earlier historic estimates first
8/9_release-check-extras: coverage, book checks, publish dry runs, packaged checks. just release-check is just test plus this
8b/9just test-fix-sbe-conformance: the FIX SBE conformance suite at its pinned commit and the Java RLValidator over ergo-sbe’s responses (also weekly in nightly.yml). Not in release-check, which the hosted release workflow runs on Java 25
8c/9just test-nri-published: installs the published ergon-shared-cpus chart and image into a throwaway kind cluster (Latency pods). Needs Docker with 6 CPUs, which a hosted runner lacks. Last run on kind: chart 0.1.6, in the 0.1.43 release

check-publish-set.sh fails if _release-pre stops running just test, if a release recipe skips _release-pre, or if either path stops reaching the dry runs.

What the workspace publishes, what it takes from crates.io, and the order of the steps:

rusteron-client 0.3
crates.io; Aeron 1.54.3
rusteron-media-driver
cluster tests and ergo-aeron's driver
rusteron-archive
ergo-aeron's optional control client
ergo-aeron-cluster
experimental Aeron Cluster
client
ergo-sbe
SBE schema → Rust codecs;
build- and runtime dep
ergon-tune
host and NIC checks;
library and CLI
ergon-shared-cpus
Helm chart 0.1.6
(NRI plugin)
ergo-sbe-inspect
run-time SBE decoding;
uses ergo-sbe
ergo-aeron-tools
driver and archive viewer;
uses ergo-sbe-inspect, rusteron
Not published
cluster-test-harness, sbe/benchmarks, samples/*, cpus,
sbe/fuzz, sbe/miri-fixtures,
sbe/inspect/oracle
before
by hand: version,
CHANGELOG, notes.
Notes file checked:
_check-release-notes
start
_reset-sources:
submodule to its pin
(release only)
1/8 supply chain
cargo deny check
cargo audit
2/8 just test
clippy, tests, samples,
Java cluster and archive,
rustdoc, benches built
3/8 Miri
UB check on the
miri fixtures
4/8 fuzz replay
six targets,
30 s each
5/8 bench gates
cluster, parity and
historic; or, in
release-verified,
evidence for HEAD
6/8 mutation
configuration only;
the full run is
manual
7/8 references
the benchmark
reference reproduces;
sbe-tool's ran in 2/8
8/9 release check
coverage, book
checks, publish
dry runs, packages
8b/9 FIX SBE
pinned conformance
suite, Java
RLValidator
8c/9 chart on kind
the published
ergon-shared-cpus
chart and image
9/9 evidence
bench archives,
fail closed
publish ergo-sbe
cargo publish
packaged cluster
unpack and build
against crates.io
publish cluster
ergo-aeron-cluster
publish the rest
ergon-tune, then
ergo-sbe-inspect,
ergo-aeron-tools
tag, release
v<version>, GitHub
release with the
bench archives
A stale diagram blocks it
8/9 runs check-book-diagrams.sh: a
diagram whose sources changed since
its stamp fails the release until it is
re-checked and restamped.
release-verified
The same gates, without the bench
re-run: 0/8 and 9/9 refuse bench
evidence that was not made for HEAD.
Bench HEAD on a quiet machine first.
Not on the path
The full mutation run,
just check-mutation (about 16 h),
stays manual; 6/8 checks its
configuration.
ergon: what it builds on, and the gates a release runs
ergon book · Verification and release › Release path
The workspace's crates and the rusteron crates they use; the steps just release echoes.
This workspace, and what it takes from crates.io
transport
codecs

The publish order is ergo-sbe, ergo-aeron-cluster, ergon-tune, ergo-sbe-inspect, ergo-aeron-tools. ergo-sbe, ergo-sbe-inspect and ergo-aeron-tools are dry-run in one cargo publish, because neither dependency is on crates.io at the new version yet. The ergo-aeron-tools verify build compiles Aeron’s C and runs its Gradle, so it needs CMake, a C compiler, libclang and a JDK 17 or newer.

just policy and the cheap gates in just preflight run at the same time (scripts/run-parallel.sh); every script runs to the end and any failure fails the recipe. The coverage ratchet runs ergo-sbe tests at default threads.

Performance method: Benchmarks (not in the crates.io package).

SBE parity gate artifacts (1.0 streak)

release.yml runs just bench and just bench-cluster, then attaches the Criterion archives (*.tar.gz) and sbe-bench-gate-no-lto.txt to the GitHub release. That output is the record for Road to 1.0 criterion 2. Run the same locally after a material codegen change:

just bench   # stamps target/bench-runs/<run-id>/ and runs the gate

Do not raise ceilings to pass.

Performance at a glance

Every figure on this page is read from a benchmark artifact in this repository by scripts/generate-performance-page.py; a measurement with no artifact reads “not measured”. Each table compares only runs of one workload and configuration. Raw runs and provenance are under Provenance.

Codec cost

ergon against sbe-tool on equal work. The ratio is ergon / sbe-tool (the range over invocations when the run repeated); the verdict is the gate’s (scripts/check-bench-gate.sh). INCONCLUSIVE passes the gate but is not parity: no winner is established. Method and ceilings: Benchmarks.

workloadlanemean costratio to sbe-tooluncertaintyverdict
decode_scalarlto510.019 ns per iteration0.9047 to 0.9197 (ceiling 1.00)ratio CI 0.8997 to 0.9253 over 5 invocation(s)PASS: resolved
decode_arraylto510.703 ns per iteration0.5824 to 0.5981 (ceiling 1.00)ratio CI 0.5768 to 0.6042 over 5 invocation(s)PASS: resolved
decode_compositelto247.912 ns per iteration0.6099 to 0.6131 (ceiling 1.00)ratio CI 0.6086 to 0.6135 over 5 invocation(s)PASS: resolved
decode_full_messagelto10530.398 ns per iteration0.7540 to 0.7678 (ceiling 1.00)ratio CI 0.7423 to 0.7779 over 5 invocation(s)PASS: resolved
decode_full_message_orderedlto10582.469 ns per iteration0.7606 to 0.7776 (ceiling 1.00)ratio CI 0.7522 to 0.7829 over 5 invocation(s)PASS: resolved
decode_entry_pointlto730.412 ns per iteration0.7060 to 0.7108 (ceiling 1.00)ratio CI 0.7040 to 0.7142 over 5 invocation(s)PASS: resolved
encode_scalar_header_and_bodylto1473.600 ns per iteration0.7010 to 0.7120 (ceiling 1.00)ratio CI 0.6979 to 0.7142 over 5 invocation(s)PASS: resolved
encode_scalar_body_onlylto294.672 ns per iteration0.7193 to 0.7731 (ceiling 1.00)ratio CI 0.7109 to 0.7867 over 5 invocation(s)PASS: resolved
encode_throughput_10klto6517.329 ns per iteration0.8758 to 0.8856 (ceiling 1.00)ratio CI 0.8686 to 0.8926 over 5 invocation(s)PASS: resolved
throughput_batch_10klto8677.831 ns per iteration0.9103 to 0.9136 (ceiling 1.00)ratio CI 0.9066 to 0.9171 over 5 invocation(s)PASS: resolved
wire_parity_encode_fulllto3790.343 ns per iteration0.6236 to 0.6333 (ceiling 1.00)ratio CI 0.6193 to 0.6392 over 5 invocation(s)PASS: resolved
extended_optional_enum_nullifylto801.339 ns per iteration0.8996 to 0.9170 (ceiling 1.00)ratio CI 0.8884 to 0.9298 over 5 invocation(s)PASS: resolved
extended_group_with_datalto4645.010 ns per iteration0.8333 to 0.8681 (ceiling 1.00)ratio CI 0.8242 to 0.8831 over 5 invocation(s)PASS: resolved
decode_scalarno-lto512.644 ns per iteration0.8771 to 0.9117 (ceiling 1.00)ratio CI 0.8731 to 0.9282 over 5 invocation(s)PASS: resolved
decode_arrayno-lto504.473 ns per iteration0.5827 to 0.5897 (ceiling 1.00)ratio CI 0.5809 to 0.5915 over 5 invocation(s)PASS: resolved
decode_compositeno-lto248.453 ns per iteration0.6106 to 0.6145 (ceiling 1.00)ratio CI 0.6097 to 0.6150 over 5 invocation(s)PASS: resolved
decode_full_messageno-lto10533.660 ns per iteration0.7582 to 0.7744 (ceiling 1.00)ratio CI 0.7572 to 0.7751 over 5 invocation(s)PASS: resolved
decode_full_message_orderedno-lto10493.759 ns per iteration0.7563 to 0.7758 (ceiling 1.00)ratio CI 0.7556 to 0.7806 over 5 invocation(s)PASS: resolved
decode_entry_pointno-lto790.586 ns per iteration0.7567 to 0.7740 (ceiling 1.00)ratio CI 0.7557 to 0.7798 over 5 invocation(s)PASS: resolved
encode_scalar_header_and_bodyno-lto1439.292 ns per iteration0.6740 to 0.6952 (ceiling 1.00)ratio CI 0.6683 to 0.6959 over 5 invocation(s)PASS: resolved
encode_scalar_body_onlyno-lto290.939 ns per iteration0.7229 to 0.7521 (ceiling 1.00)ratio CI 0.7135 to 0.7616 over 5 invocation(s)PASS: resolved
encode_throughput_10kno-lto6485.409 ns per iteration0.8748 to 0.8814 (ceiling 1.00)ratio CI 0.8725 to 0.8889 over 5 invocation(s)PASS: resolved
throughput_batch_10kno-lto8507.867 ns per iteration0.9018 to 0.9210 (ceiling 1.00)ratio CI 0.8988 to 0.9253 over 5 invocation(s)PASS: resolved
wire_parity_encode_fullno-lto4502.449 ns per iteration0.7453 to 0.7509 (ceiling 1.00)ratio CI 0.7437 to 0.7526 over 5 invocation(s)PASS: resolved
extended_optional_enum_nullifyno-lto776.695 ns per iteration0.8860 to 0.8883 (ceiling 1.00)ratio CI 0.8813 to 0.8964 over 5 invocation(s)PASS: resolved
extended_group_with_datano-lto4785.088 ns per iteration0.8060 to 0.8591 (ceiling 1.00)ratio CI 0.7902 to 0.8752 over 5 invocation(s)PASS: resolved
cluster_encode_session_message_headerlto2.790 ns per op0.9836 to 1.0514 (ceiling 1.00)ratio CI 0.9720 to 1.0631 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_encode_session_keep_alivelto1.895 ns per op0.9433 to 1.0586 (ceiling 1.00)ratio CI 0.9347 to 1.0687 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_decode_session_message_headerlto1.276 ns per op0.9520 to 1.0465 (ceiling 1.01)ratio CI 0.9429 to 1.0904 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_decode_session_eventlto2.625 ns per op0.8068 to 0.8491 (ceiling 1.01)ratio CI 0.7995 to 0.8725 over 5 invocation(s)PASS: resolved
cluster_encode_claim_shaped_header_plus_applto4.425 ns per op0.9555 to 1.0521 (ceiling 1.00)ratio CI 0.9462 to 1.0636 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_encode_session_message_headerno-lto2.650 ns per op0.9506 to 1.0037 (ceiling 1.00)ratio CI 0.9413 to 1.0129 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_encode_session_keep_aliveno-lto1.924 ns per op0.9906 to 1.0732 (ceiling 1.00)ratio CI 0.9801 to 1.0835 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band
cluster_decode_session_message_headerno-lto1.213 ns per op0.9325 to 1.0031 (ceiling 1.01)ratio CI 0.9257 to 1.0079 over 5 invocation(s)PASS: resolved
cluster_decode_session_eventno-lto2.761 ns per op0.8941 to 0.9555 (ceiling 1.05)ratio CI 0.8882 to 0.9732 over 5 invocation(s)PASS: resolved
cluster_encode_claim_shaped_header_plus_appno-lto4.447 ns per op0.9512 to 1.0393 (ceiling 1.00)ratio CI 0.9422 to 1.0474 over 5 invocation(s)INCONCLUSIVE: no winner: inside the measured A/A band

Codec cost distribution

Per arm, runs of one profile pooled over every invocation. n is the number of Criterion samples; min, p50, p99, p99.99 and max are percentiles of the per-sample cost (ns per iteration for sbe codecs, ns per operation for cluster codecs). A sample is the mean of a batch of iterations, so these are not per-message tails: the max is the slowest sample’s mean, and with n below 10,000 p99.99 is that max. Each max is unexplained: the host was shared with other jobs while these ran, so a spike may be preemption or cache pollution; the next experiment is a rerun on an isolated CPU.

workloadlanearmnminp50p99p99.99max
decode_scalarltoergo-sbe1,000488.618507.866534.909538.927538.927
decode_scalarltosbe-tool1,000540.439552.411608.333613.032613.032
decode_arrayltoergo-sbe1,000489.799505.217544.869784.579784.579
decode_arrayltosbe-tool1,000851.780857.966897.0321269.0031269.003
decode_compositeltoergo-sbe_engine1,000240.874247.704250.066254.325254.325
decode_compositeltosbe-tool_engine1,000402.324404.675411.810547.861547.861
decode_full_messageltoergo-sbe_consuming1,00010390.10410481.07510959.91218856.09218856.092
decode_full_messageltosbe-tool1,00013434.97813760.52714164.59133050.36833050.368
decode_full_message_orderedltoergo-sbe_ordered1,00010432.66210557.13910856.54016418.24916418.249
decode_full_message_orderedltosbe-tool1,00013434.97813760.52714164.59133050.36833050.368
decode_entry_pointltoergo-sbe_wrap1,000648.069730.248810.972833.716833.716
decode_entry_pointltosbe-tool_wrap1,000966.4161030.9431058.0981089.7741089.774
encode_scalar_header_and_bodyltoergo-sbe_header_and_body1,0001443.6031468.6821527.4741577.8141577.814
encode_scalar_header_and_bodyltosbe-tool_header_and_body1,0001969.8362087.1912148.8742792.1532792.153
encode_scalar_body_onlyltoergo-sbe_body_only1,000265.606281.897368.440562.761562.761
encode_scalar_body_onlyltosbe-tool_body_only1,000381.545395.612413.117558.007558.007
encode_throughput_10kltoergo-sbe1,0006012.4686523.7186722.7569759.8319759.831
encode_throughput_10kltosbe-tool1,0006823.1017386.7107541.17611146.56811146.568
throughput_batch_10kltoergo-sbe1,0008539.4978655.5288947.0498987.2718987.271
throughput_batch_10kltosbe-tool1,0009279.6709467.92510129.89010287.56410287.564
wire_parity_encode_fullltoergo-sbe1,0003513.6593789.0273904.5826556.5436556.543
wire_parity_encode_fullltosbe-tool1,0005713.1426023.7956179.7208771.5868771.586
extended_optional_enum_nullifyltoergo-sbe1,000721.001773.4941011.6641032.0281032.028
extended_optional_enum_nullifyltosbe-tool1,000847.898877.620921.430934.060934.060
extended_group_with_dataltoergo-sbe1,0004553.2674579.6035420.4186194.1846194.184
extended_group_with_dataltosbe-tool1,0005256.3915342.3336198.8186833.9676833.967
decode_scalarno-ltoergo-sbe1,000487.316506.533554.6461145.3091145.309
decode_scalarno-ltosbe-tool1,000544.768576.351616.021627.491627.491
decode_arrayno-ltoergo-sbe1,000487.075502.552525.231533.184533.184
decode_arrayno-ltosbe-tool1,000850.498858.886867.929875.373875.373
decode_compositeno-ltoergo-sbe_engine1,000242.921248.136251.496254.230254.230
decode_compositeno-ltosbe-tool_engine1,000403.015405.259415.447420.502420.502
decode_full_messageno-ltoergo-sbe_consuming1,00010359.48110495.27310721.11310762.95810762.958
decode_full_messageno-ltosbe-tool1,00013456.73113780.68113918.26914239.92914239.929
decode_full_message_orderedno-ltoergo-sbe_ordered1,00010326.73710455.37210785.66515474.57615474.576
decode_full_message_orderedno-ltosbe-tool1,00013456.73113780.68113918.26914239.92914239.929
decode_entry_pointno-ltoergo-sbe_wrap1,000708.229781.702844.400874.207874.207
decode_entry_pointno-ltosbe-tool_wrap1,000984.7861030.9861078.0171082.7811082.781
encode_scalar_header_and_bodyno-ltoergo-sbe_header_and_body1,0001268.7381444.9681458.1651500.5541500.554
encode_scalar_header_and_bodyno-ltosbe-tool_header_and_body1,0001994.3062086.7042131.0812157.7712157.771
encode_scalar_body_onlyno-ltoergo-sbe_body_only1,000257.467270.477321.097327.169327.169
encode_scalar_body_onlyno-ltosbe-tool_body_only1,000380.250395.387414.688616.779616.779
encode_throughput_10kno-ltoergo-sbe1,0006120.0346460.4926744.09310582.57810582.578
encode_throughput_10kno-ltosbe-tool1,0006915.3167392.8237465.8327504.7947504.794
throughput_batch_10kno-ltoergo-sbe1,0008365.8518474.5208753.80112040.68212040.682
throughput_batch_10kno-ltosbe-tool1,0009111.7309339.6849789.4989832.5589832.558
wire_parity_encode_fullno-ltoergo-sbe1,0004209.5354508.3034560.3684620.4954620.495
wire_parity_encode_fullno-ltosbe-tool1,0005626.4016018.4846179.9186206.9286206.928
extended_optional_enum_nullifyno-ltoergo-sbe1,000707.878772.894880.2331206.3051206.305
extended_optional_enum_nullifyno-ltosbe-tool1,000841.266876.160913.192928.637928.637
extended_group_with_datano-ltoergo-sbe1,0004550.4304584.2186086.8807541.8277541.827
extended_group_with_datano-ltosbe-tool1,0005520.2135590.4986448.6097124.4347124.434
cluster_encode_session_message_headerltoergo-sbe2,0002.5612.7563.2513.5093.509
cluster_encode_session_message_headerltosbe-tool2,0002.5562.7543.2373.4313.431
cluster_encode_session_keep_aliveltoergo-sbe2,0001.7881.8582.2772.4602.460
cluster_encode_session_keep_aliveltosbe-tool2,0001.7841.8992.2352.5792.579
cluster_decode_session_message_headerltoergo-sbe2,0001.1831.2342.4023.2873.287
cluster_decode_session_message_headerltosbe-tool2,0001.1821.2042.3572.8892.889
cluster_decode_session_eventltoergo-sbe2,0002.5092.5444.2864.5164.516
cluster_decode_session_eventltosbe-tool2,0002.9543.1403.9694.1934.193
cluster_encode_claim_shaped_header_plus_appltoergo-sbe2,0004.0414.3725.1235.8695.869
cluster_encode_claim_shaped_header_plus_appltosbe-tool2,0004.0754.3975.1395.5185.518
cluster_encode_session_message_headerno-ltoergo-sbe2,0002.5332.6172.9603.1933.193
cluster_encode_session_message_headerno-ltosbe-tool2,0002.5342.6623.1674.4064.406
cluster_encode_session_keep_aliveno-ltoergo-sbe2,0001.7921.8962.2742.5722.572
cluster_encode_session_keep_aliveno-ltosbe-tool2,0001.7911.8472.1422.3782.378
cluster_decode_session_message_headerno-ltoergo-sbe2,0001.1851.2011.3311.4391.439
cluster_decode_session_message_headerno-ltosbe-tool2,0001.1821.2211.4051.6741.674
cluster_decode_session_eventno-ltoergo-sbe2,0002.6582.6973.1884.3774.377
cluster_decode_session_eventno-ltosbe-tool2,0002.9532.9573.8235.8475.847
cluster_encode_claim_shaped_header_plus_appno-ltoergo-sbe2,0004.0264.4105.1925.5125.512
cluster_encode_claim_shaped_header_plus_appno-ltosbe-tool2,0004.0684.4315.2215.9985.998

Individual-message latency

One codec operation per sample, as the latency_distribution bench (just bench-diagnostics) times it. No run of it is kept here.

workloadloadnminp50p99p99.99maxmax causethroughputdrops
codec, one operation per samplenot measurednot measurednot measurednot measurednot measurednot measurednot measurednot measurednot measurednot measured

Failover

scenariofailure detectionunavailable intervaltime to valid book
cluster leader failovernot measurednot measurednot measured

The failover tests (cluster-test-harness/tests/failover.rs and failover_own_driver.rs) check that the client reconnects to the new leader within a deadline, not how long it takes.

Host scheduling gaps

A busy-spin loop on an isolated CPU, with helper load on the pod’s shared CPU: every loop iteration in ns, reps of one arm pooled. n is loop iterations; p50, p99 and p99.99 are histogram bucket upper bounds; min is the lowest bucket’s bound; max is exact. Gap-log drops are gaps the probe could not log, not lost messages. Setup and fixes: Shared CPUs.

armrepsnminp50p99p99.99maxgap-log dropsmax cause
plugin-on37,463,469,071≤ 82432325,5200host stall below the guest kernel (hypervisor or hardware) (rep 3: 0 involuntary switches (rep total); interrupts overlapping: nothing counted)

Under ftrace (trace): the tracer adds its own cost, so these are not comparable with the table above.

armrepsnminp50p99p99.99maxgap-log dropsmax cause
trace12,488,258,738≤ 824323240,6080preemption: a kworker LRU drain after systemd’s daily generators (node event) (rep 1: 1 involuntary switch (rep total); interrupts overlapping: IPI0 Rescheduling interrupts +1, IPI1 Function call interrupts +1)

Provenance

  • Codec cost, sbe lto: estimates and gate output (run_id b20261106T083837Z-61963-af10a56ac3fb, commit af10a56ac3fb36e99c332e6e53aa3d38a5131393, rustc 1.99.0 (b940084d7 2026-09-28), target aarch64-apple-darwin, host Apple M4).
  • Codec cost, sbe no-lto: estimates and gate output (run_id b20261106T083837Z-61963-af10a56ac3fb, commit af10a56ac3fb36e99c332e6e53aa3d38a5131393, rustc 1.99.0 (b940084d7 2026-09-28), target aarch64-apple-darwin, host Apple M4).
  • Codec cost, cluster lto: estimates and gate output (run_id cluster-20261106T151023Z-c8d9b86, commit c8d9b8646a52a01ac1fee48265d09f6ea7d4a18f, rustc 1.99.0 (b940084d7 2026-09-28), target x86_64-unknown-linux-gnu, host Intel(R) Core(TM) i5-8500T CPU @ 2.10GHz; load at start: 23:10:23 up 3:02, 7 users, load average: 0.43, 1.37, 2.33; load at end: 23:26:40 up 3:19, 8 users, load average: 2.01, 2.74, 2.73).
  • Codec cost, cluster no-lto: estimates and gate output (run_id cluster-20261106T151023Z-c8d9b86, commit c8d9b8646a52a01ac1fee48265d09f6ea7d4a18f, rustc 1.99.0 (b940084d7 2026-09-28), target x86_64-unknown-linux-gnu, host Intel(R) Core(TM) i5-8500T CPU @ 2.10GHz; load at start: 23:26:40 up 3:19, 8 users, load average: 2.01, 2.74, 2.73; load at end: 23:42:22 up 3:34, 8 users, load average: 2.74, 2.61, 2.62).
  • Host scheduling gaps: run azure-20261024234841, Standard_D8ps_v6 (8 vCPUs, aarch64), Debian GNU/Linux 13 (trixie), kernel 6.12.113+deb13-cloud-arm64.
  • Max causes: max-causes.tsv.

Road to 1.0

Every published crate is 0.x alpha and not production-ready. This page gives the exit criteria for ergo-sbe and ergo-aeron-cluster: criteria, not a date.

Breaking changes on 0.x

Rule0.x
API breaksAllowed in any release
Deprecation periodNone: an item is removed or changed in place
RecordCHANGELOG.md lists every break
Wire formatNot covered: official SBE wire compatibility still holds

ergo-sbe (reaches 1.0 first)

Ship 1.0.0 of ergo-sbe only when all of the following hold:

  1. API freeze audit complete: decisions in API freeze are stable; no pending renames of generated stage / wrap / FixedFields surface without a major.
  2. Parity gate: every maintained ergon vs sbe-tool comparison passes the benchmark gate in both LTO profiles for three consecutive releases, with the gate output attached to each release. Ceilings and the inconclusive rule: sbe/BENCHMARKS.md.
  3. Wire compatibility: dual-encode parity tests and golden API shape remain green; no deliberate wire break without a major.
  4. Trust boundary: fuzz corpus on decode entry stays green in CI; Miri fixtures for unaligned paths stay green; no known P0 safety issues open.
  5. Docs: book chapters for migration (sbe-tool), trust boundaries, buffer sizing, and type-state design notes are published and linked from the crate README.
  6. External signal: at least one external user (or production pilot) has reported wire + latency results against their own schema, or an equivalent published case study in the repo.

Until then the disclaimer stays, but it points here instead of reading as a permanent warning.

ergo-aeron-cluster (separate clock)

Cluster 1.0 is not tied to sbe 1.0. Additional criteria (illustrative):

  • Stable session lifecycle and error types under multi-node test harness
  • Documented Aeron version matrix and rusteron compatibility
  • Codec generation locked to a released ergo-sbe major
  • Separate performance gate (just bench-cluster) with recorded baselines

Cluster may remain 0.x after sbe 1.0.

What 1.0 is not

  • Not “feature complete for every SBE edge case in every venue schema”
  • Not a promise that your schema’s latency matches the car/L3 benches
  • Not a freeze of optional config knobs’ defaults without changelog

Tracking

  • Release process: Verification and release.
  • Changelog: repository root CHANGELOG.md.
  • External pilot: External schema pilot.
  • Cluster compatibility: Cluster compatibility.
  • Generated API snapshots: scripts/check-generated-public-api.sh diffs generated codec surfaces against api/generated/*.txt, so every surface change is reviewed. It tracks changes; it does not forbid them.
  • Benchmark evidence: just bench + just bench-cluster write provenance-stamped Criterion trees; scripts/package-bench-artifacts.sh attaches them to a GitHub release. A number without a matching run-id / HEAD commit is not evidence.

Status

A claimed 1.0 streak tag must be an ancestor of main (git merge-base --is-ancestor <tag> main), not merely a GitHub Release. git describe --tags is not the check.

CriterionStatus
1. API-freeze auditOpen. Generated-API snapshot diffs (api/generated/) track every surface change.
2. Parity gateOpen. Needs three consecutive releases on main with gate output attached.
3. Wire compatibilityDual-encode parity tests run in CI. FIX SBE conformance: suite tests 1–3 run in CI; the RLValidator leg runs weekly and in just release, not per push (External pilot).
4. Trust boundaryFuzz + Miri fixtures exist; any open P0 is blocking.
5. DocsBook + migration pages published.
6. External signalOpen. In-repo FIX SBE is internal evidence, not an external user. See external-pilot.md.
Cluster 1.0Separate clock; compatibility + just bench-cluster exist.

External schema pilot

The 1.0 exit criterion requires an external user or production pilot with wire and latency results against their own schema, not only in-repo tests.

Status: open

The FIX SBE conformance suite (sbe/tests/fix_sbe_conformance_test.rs, fixtures, and scripts/run-fix-sbe-conformance.sh) is necessary internal wire evidence. It is not the 1.0 external-signal criterion: there is no external user, no independent schema family, and no latency measurement from outside this repository.

Treat this page as the checklist for that missing signal, not a completed exit item.

What the conformance suite covers here

PartRuns in CISource
Byte-identity of ergon responses against Real Logic’s goldens, suite tests 1–3yes (cargo test -p ergo-sbe)sbe/tests/fix_sbe_conformance_test.rs
Official RLValidator over ergon’s responsesweekly in nightly.yml and in just release, not per push: compiled only with --cfg ergon_rlvalidator, which ci.yml does not set. With the cfg, a missing suite failsoptional_java_rlvalidator_accepts_ergon_equivalent_responses

scripts/run-fix-sbe-conformance.sh (just test-fix-sbe-conformance) fetches the suite at the commit in scripts/fix-sbe-conformance-pin.txt, builds it, sets FIX_SBE_CONFORMANCE_HOME, compiles that test with --cfg ergon_rlvalidator and runs it by name. A suite at any other commit, a missing suite directory, an unbuilt target/classes or a classpath failure stops the script. The pin means this leg’s verdict does not move with an upstream push; it is still the same conformance suite ergon is compared with, so it stays internal evidence and this pilot stays open.

Commands

# Byte-identity only. The RLValidator test is not compiled.
cargo test -p ergo-sbe --test fix_sbe_conformance_test --all-features

# RLValidator leg: built Java suite, and the cfg that compiles the test.
RUSTFLAGS="--cfg ergon_rlvalidator" \
  FIX_SBE_CONFORMANCE_HOME=/path/to/suite \
  cargo test -p ergo-sbe --all-features \
  --test fix_sbe_conformance_test optional_java_rlvalidator_accepts_ergon_equivalent_responses

Package scope

crates.io ships each crate’s source, its README, and the manifest.

Not published: tests, fixtures, samples, benches, the book, Java harnesses, and upstream reference trees. Those live on GitHub.

Cratecrates.io
ergo-sbegenerator
ergo-aeron-clusterCluster client
ergon-tunehost and NIC checks
ergo-sbe-inspectrun-time decoding and the sbe-inspect filter
ergo-aeron-toolsergo-aeron

Samples, ergo-sbe-benchmarks, ergo-aeron-cluster-test-harness, ergo-cpus, ergo-sbe-inspect-oracle (test support), ergo-sbe-fuzz and ergo-sbe-miri-fixtures are publish = false. Cluster codecs are #[doc(hidden)] pub in cluster_codec_types, re-exported for integration tests and benches only, not a stable consumer API. Use AeronCluster for normal usage.

Apache-2.0.