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

predsync is a deterministic, low-bandwidth protocol for replicating predictor state across an uncontrolled, lossy, one-way link. It is a codec-shaped library: your application owns the transport, scheduling and threading; predsync owns the bytes and the receiver’s trust in each field.

The sender predicts a field from its recent history. When the prediction is close enough to the value the receiver would see, the field is omitted. When it is not, the field is included or refreshed. Periodic Reset frames let a receiver that missed earlier frames recover without a back channel.

What this library provides

  • A schema language that fixes field order, types, wire widths, predictors and recovery periods.
  • A byte-exact encoder and decoder with no hidden global state.
  • Deterministic frame bytes and predictor-state hashes across platforms.
  • Alloc, fixed-storage (no-alloc) and caller-owned buffer paths in Rust.
  • C bindings, Python bindings and generated typed wrappers.
  • Golden vectors, differential tests, fuzz targets and a cross-architecture determinism check.

What this library does not provide

  • It is not middleware: it does not choose a transport, discover peers or retry frames.
  • It is not a general compressor: omission is driven by declared predictors and tolerances.
  • It is not a ROS 2 layer: the ROS 2 example is only one possible host.
  • It does not identify senders. Use one encoder per sender and one decoder per incoming stream.

The five guarantees

  1. Bound. Every delivered Predicted value is within the field’s tolerance of the sender’s true value after quantisation and casting.
  2. No silent staleness. After a gap, decode failure or startup, affected fields are Unknown until re-validated. The documented exception is losing exactly a multiple of 256 consecutive frames.
  3. Self-stabilisation. A delivered Reset makes the decoder’s field state equal to the encoder’s.
  4. Determinism. Identical inputs produce identical bytes and predictions on every supported platform.
  5. Containment. A rejected frame leaves decoder state unchanged, apart from the documented diagnostic counters.

See Guarantees for the precise wording and measured costs.

Reading this book

Start with a quickstart, then read the schema language and protocol chapters before choosing an API. Embedded users should also read Embedded and no-alloc use. The examples chapters show complete host programs for UDP, serial/COBS, ROS 2 and generated wrappers.

API Documentation

The generated API references are available for each language:

Quickstart

All bindings use the same schema and the same frame format. Pick the language that matches your host application:

  • Rust — the primary API, with alloc and fixed-storage paths.
  • Python — PyO3 bindings for scripting and ROS 2 hosts.
  • C — a stable C ABI for embedded hosts and FFI consumers.
  • Command line — validate a schema set before deploying it.

Every sender needs its own Encoder; every incoming stream needs its own Decoder. A schema set may contain several message types, but the message ID byte only dispatches within one stream. It is not a sender identity.

Rust quickstart

Add the facade crate to your application:

[dependencies]
predsync = "=0.1.0"

predsync re-exports predsync_core as predsync::core, predsync_schema as predsync::schema and predsync_compiler as predsync::compiler. The default features enable alloc and compiler. Embedded applications should set default-features = false, optionally enable alloc, and use generated wrappers instead of runtime YAML parsing.

use predsync::{parse_schema, Decoder, DecoderConfig, Encoder, EncoderConfig, Slot, Value};

const SCHEMA: &str = r#"
name: telemetry
sync:
  refresh: 8
  reset: 32
fields:
  - name: x
    type: f64
    quantise: 0.01
    range: [-100.0, 100.0]
    predictor: { type: linear, window: 4 }
    tolerance: { abs: 0.01 }
"#;

fn main() {
    let set = parse_schema(SCHEMA).unwrap().set;
    let mut encoder = Encoder::new(&set, 0, EncoderConfig::default()).unwrap();
    let mut decoder = Decoder::new(&set, DecoderConfig { resync_n: 1 }).unwrap();

    for tick in 0..3u64 {
        let values = [Value::Scalar(Slot::from_f64(1.25))];
        let plan = encoder.plan(&values, tick * 1_000_000).unwrap();
        let mut frame = vec![0u8; plan.len];
        encoder.commit(plan, &mut frame).unwrap();

        let decoded = decoder.feed(&frame).unwrap();
        assert_eq!(decoded.fields[0].value, values[0]);
    }
}

plan decides which fields are sent; commit writes the bytes. Splitting the two calls lets you size a fixed output buffer from plan.len. Use Encoder::encode when a Vec is acceptable.

The first frame is a startup Reset. Later frames omit x while the prediction stays within abs: 0.01 of the quantised truth. Decoder::feed takes no wall clock argument: it derives predictor time only from the wire ticks.

Multiple senders

Frames carry no sender identity. Give each sender its own Encoder, and give each incoming stream its own Decoder. The optional message-ID byte selects one message type inside a single stream; it does not select a sender.

No allocation

For fixed-storage targets, use Encoder::with_storage, Decoder::with_storage and the generated SCHEMA_REF/STORAGE_LAYOUT. See Embedded and no-alloc use and the generated example.

Python quickstart

Install the wheel (or run pixi run python-build in a source checkout):

python -m pip install predsync

The wheel does not bundle schema files. Copy a .yaml schema into your project and load it from a path. The example below assumes a source checkout and is run from the repository root; it uses the same four-field demo schema as the generated Telemetry class.

from pathlib import Path

import predsync
from predsync.generated import Telemetry, TelemetryMode

schema_yaml = Path("examples/generated_example/schema/telemetry.yaml").read_text()
sample = Telemetry(
    x=1.25,
    mode=TelemetryMode.Active,
    label="nominal",
    samples=[7, 8, 9],
)

encoder = predsync.Encoder(schema_yaml, message=Telemetry.message_index, tick_ns=1_000_000)
decoder = predsync.Decoder(schema_yaml, message=Telemetry.message_index, resync_n=1)

for tick in range(3):
    frame, _info = encoder.encode(sample.to_values(), tick * 1_000_000)
    decoded = decoder.feed(frame)
    assert Telemetry.from_values(decoded.values()) == sample

encode accepts either a field-name dictionary or a schema-order list. Decode returns native Python values plus validity metadata in decoded.fields; enums are represented by variant names.

Generated classes

Telemetry in the example above is a generated class from predsync.generated. It exposes to_values() and from_values(), and carries schema_yaml, message_index and field_names so engines can be created without a second schema copy. TelemetryMode is the generated enum; its members are the schema variant names.

See Python API and the ROS 2 example.

C quickstart

The C ABI is a static library plus the generated header crates/ffi/include/predsync.h. Link against libpredsync_ffi.a; every entry point returns a PredsyncStatus.

#include "predsync.h"
#include <stdint.h>
#include <string.h>

static const char SCHEMA[] =
    "name: telemetry\n"
    "sync: { refresh: 8, reset: 32 }\n"
    "fields:\n"
    "  - name: x\n"
    "    type: f64\n"
    "    quantise: 0.01\n"
    "    range: [-100.0, 100.0]\n"
    "    predictor: { type: linear, window: 4 }\n"
    "    tolerance: { abs: 0.01 }\n";

int send_one_frame(void) {
    PredsyncSet *set = NULL;
    PredsyncEncoder *encoder = NULL;
    uint64_t bits = 0;
    double value = 1.25;
    uint8_t frame[256];
    uintptr_t frame_len = 0;
    PredsyncEncodeInfo info;
    uint32_t error = 0;
    int result = 1;

    memcpy(&bits, &value, sizeof bits);
    PredsyncValue values[1] = {{
        Scalar, F64, bits, NULL, 0, 0
    }};

    if (predsync_set_from_yaml(SCHEMA, strlen(SCHEMA), &set) != Ok) {
        return 1;
    }
    if (predsync_encoder_new(set, 0, 1000000ULL, 0xffff, &encoder) != Ok) {
        goto done;
    }
    if (predsync_encode(encoder, values, 1, 0, frame, sizeof frame,
                        &frame_len, &info, &error) == Ok) {
        result = 0; /* pass frame, frame_len to your transport */
    }

done:
    if (encoder != NULL) {
        predsync_encoder_free(encoder);
    }
    predsync_set_free(set);
    return result;
}

The library never owns a caller buffer. Strings and lists are borrowed on encode; decoded strings and lists are copied into caller-provided capacity. See the C API reference and the complete C quickstart example.

Command line

The predsync facade crate provides two commands through the predsync binary: schema_check validates receiver schema sets, and schema_build generates typed Rust wrappers from them. Both accept hyphenated aliases (schema-check, schema-build). Install the tool with cargo install predsync --locked.

Use the pixi tasks, or call the binary directly with Cargo:

pixi run schema-check --set examples/schema_sets/alpha --set examples/schema_sets/beta
pixi run schema-build --set examples/generated_example/schema/telemetry.yaml --out src/telemetry.rs
cargo run -p predsync --bin predsync -- \
  schema_check --set examples/schema_sets/alpha --set examples/schema_sets/beta

cargo run -p predsync --bin predsync -- \
  schema_build --set examples/generated_example/schema/telemetry.yaml --out src/telemetry.rs

A set path may be a YAML file or a directory of .yaml files. --set may be repeated; sets are checked independently and then compared for inconsistent IDs. Neither command needs network access.

schema_check

schema_check parses and validates every schema, then prints a deterministic table with one row per message per set, sorted by qualified name and set label. Set labels are path file names, not absolute paths. It has no side effects.

predsync schema_check --set <dir-or-file> [--set <dir-or-file>...]

schema_build

schema_build runs the same checks, then writes one generated Rust module to --out. Parent directories are created if needed. Generation is deterministic: the same sets always produce the same bytes, so the output is safe to commit or include! directly.

predsync schema_build --set <dir-or-file> [--set <dir-or-file>...] --out <file>

The generated module contains namespace and message modules, ID and FIELD_* constants, enum types, message structs with to_values()/from_values(), and the SCHEMA_REF, STORAGE_LAYOUT and generated PredictorSet items described in Generated wrappers.

schema_build generates Rust only. Use generate_python or generate_c from the predsync_compiler library for other languages. Schemas that use custom predictors still need a build.rs so the predictor implementations can be registered with Builder::custom_predictor.

Exit codes

Codeschema_checkschema_build
0All checks passed.Checks passed and the module was written.
1A set was invalid or an ID collided.A set was invalid, code generation failed, or the output could not be written.
2The command line was malformed.The command line was malformed.

predsync help prints the usage lines.

Schema language

A schema is the contract between sender and receiver. Both ends must use the same schema; the encoder’s schema hash is part of generated state and custom predictor declarations are folded into the fingerprint. The compiler parses a small YAML subset and rejects anything outside it.

namespace: robot        # optional; qualifies the message name
name: pose              # required identifier
id: 12                  # optional 0..=255 override of the derived message ID
sync:                   # optional defaults for every predictor field
  refresh: 10           # K: send a true value every 10 committed frames
  reset: 50             # K_R: reset receiver state every 50 committed frames
  max_resets_per_frame: 1
enums:                  # optional, scoped to this message
  - name: Status
    variants: [Idle, Moving, Fault]
fields:                 # ordered sequence; wire order follows declaration order
  - name: x
    type: f32
    quantise: 0.01
    range: [-100.0, 100.0]
    predictor: { type: linear, window: 5 }
    tolerance: { abs: 0.01, rel: 0.01, mode: all }
  - name: flags
    type: u8            # no predictor: always included in the payload
  - name: mode
    type: Status
    predictor: { type: hold_last }
  - name: waypoint_ids
    type: [u16]  # one-element sequence; max_len is mandatory for strings and lists
    max_len: 32
  - name: label
    type: string
    max_len: 64
    predictor: { type: hold_last }

Identifiers and message IDs

name, field names, enum names and enum variant names match [A-Za-z_][A-Za-z0-9_]*. The qualified name is namespace.name when a namespace is present, otherwise name. The message ID is a folded FNV-1a 32-bit hash of the qualified name; an explicit id overrides it. Use predsync schema_check to detect ID collisions within a set and inconsistent IDs across receiver sets.

Field types

TypeWire representation
bool1 bit
u8, u16, u32, u64little-endian two’s complement, native width
i8, i16, i32, i64little-endian two’s complement, native width
f32, f64raw IEEE bits unless quantised
A message enummax(1, ceil_log2(n_variants)) bits holding the variant index
string16-bit byte length, then UTF-8 bytes
[T]16-bit element count, then bit-packed elements of scalar or enum type T

A list type is written as a one-element YAML sequence, for example type: [u16].

Nested lists, lists of strings and maps are not supported in v1. Every string or list field must declare max_len in 1..=65535; the decoder validates wire lengths against it before allocating or copying.

Predictors and tolerance

The predictor discriminator is type, as in predictor: { type: linear, window: 5 }.

Numeric fields may use linear, quadratic, cubic, ewma or hold_last, and must declare a tolerance. window is required for polynomial predictors and must be at least the number of samples the fit needs: 2 for linear, 3 for quadratic, 4 for cubic. The maximum window is 64. ewma instead requires alpha in (0, 1] and must not declare window; alpha is only valid for ewma. The smoothing factor is folded into the schema fingerprint, so two ends with different alpha values cannot silently agree.

bool, enum, string and list fields may use only hold_last and must not declare a tolerance: equality is exact on the final value. quantise and range are allowed on numeric scalars and lists of numeric scalars.

Tolerance supports abs, rel and mode. With both bounds present, mode: all requires both to pass and mode: any requires either. The auto key is recognised but rejected with Unsupported("auto tolerance") in v1.

refresh (K) and reset (K_R) may be set per field or in the message sync: block. K_R must be a multiple of K, and K must be at least the predictor window when the predictor has one (ewma and hold_last do not). A predictor field with no recovery period anywhere is valid but produces a warning: after a link gap it can only recover if a startup Reset happens to arrive.

Custom predictors

Custom predictor names are declared at the API boundary (Builder in Rust, Registry in Python/C) rather than in the YAML grammar. A custom declaration has a name, a window, optional ordered numeric params and an optional integer version. Unregistered names fail at generation or construction time. The name, window, parameters and version are folded into the schema fingerprint so the two ends cannot silently run different models. Callback models written in C or Python are outside the cross-platform bit-exactness guarantee.

Validation is deterministic

Fields are stored and validated in declaration order; maps never influence output. Every rejected schema produces a specific SchemaError variant rather than a generic parse failure. See the API guides for the error types exposed by each language.

Protocol

This part is the public wire contract. A frame carries one message, a sequence number, wire ticks, predictor presence codes, a bit-packed payload and a CRC.

The protocol is deliberately small:

  • Bits are packed least-significant bit first; multi-byte integers are little-endian.
  • The receiver never supplies a wall clock to feed; it uses wire ticks only.
  • Sequence numbers are 8 bits and wrap at 256.
  • Every rejected frame must leave predictor state unchanged.

Read the chapters in order:

The golden vectors in tests/vectors/ and the Python reference model in tests/reference/ are executable interpretations of this contract. They are part of the test suite, not optional examples.

Frame format

[ message_id : 1 byte, only when the schema set has more than one message ]
[ sequence   : 1 byte, wrapping mod 256 ]
[ ticks      : 2 bytes, little-endian, wrapping mod 65,536 ]
[ presence   : ceil(2 * n_pred / 8) bytes ]
[ payload    : bit-packed, padded with zero bits to a byte boundary ]
[ crc16      : 2 bytes, little-endian, over every preceding byte ]

n_pred is the number of fields with a predictor, counted in schema order. Fields without a predictor have no presence bits and are always in the payload.

Presence codes

Each predictor field has a two-bit code at bits 2k and 2k+1, counting least-significant bit first across the presence bytes:

CodeNameMeaning
0PredictedField omitted; receiver uses its predictor.
1IncludedTrue value is present in the payload.
2RefreshTrue value is present; receiver checks it against its prediction.
3ResetTrue value is present; receiver resets predictor state, then updates it.

Unused high bits are zero. For a one-message set with sequence 5, wire ticks 0x0102, and three predictor fields with codes [Reset, Included, Predicted], the bytes before the payload are 05 02 01 07: the presence byte is 3 | (1 << 2) | (0 << 4) = 0x07.

Payload order

All fields appear in schema order. A field is present if it has no predictor or its presence code is not Predicted. Variable-length fields carry their own 16-bit length, so the payload length depends on the values. plan computes the exact frame length from the proposed presence codes; commit writes into the caller’s buffer.

CRC and message ID

The CRC is CRC-16/IBM-SDLC (X.25): polynomial 0x1021, reflected input and output, initial value 0xFFFF, final XOR 0xFFFF. The check value for the ASCII bytes 123456789 is 0x906E.

The message ID is computed from FNV-1a 32-bit over the UTF-8 qualified name:

h  = fnv1a32(name)
id = (h ^ (h >> 8) ^ (h >> 16) ^ (h >> 24)) & 0xFF

Minimum frame

The shortest valid frame is header (1 or 2) + 2 ticks + presence + 2 CRC bytes. Frames shorter than that are rejected as TooShort. Unknown message IDs, bad CRCs and malformed payloads are rejected before any predictor state changes.

Value encoding

Slots

All scalar values cross the Rust API as Slot(u64):

  • unsigned integers are zero-extended;
  • signed integers are sign-extended by as u64;
  • bool is 0 or 1;
  • f32 is f32::to_bits() as u64;
  • f64 is f64::to_bits();
  • an enum is its zero-based variant index.

Value wraps a scalar slot, a list of slots, or a UTF-8 string. A decoded field also carries a Validity.

Final values and quantisation

For a field with quantise: step, the sender computes q = round_half_away_from_zero(v / step). If range: [lo, hi] is declared, the quantised bounds are round(lo / step) and round(hi / step) and q is clamped to them. Otherwise q is clamped to the signed range of the wire width. Clamping sets bound_applies = false for that field and frame.

The receiver emits the final value:

  • quantised field: cast(q * step);
  • unquantised field: cast(v);
  • f32: round to f32, then widen to f64;
  • integer: round half away from zero, then saturate to the type’s range;
  • bool: 1.0 when x >= 0.5, otherwise 0.0.

Both ends update their predictors with final values, never with raw input. That is what makes the tolerance check meaningful: it compares the sender’s true value as the receiver would emit it with the value the receiver actually emits.

Wire widths

Field kindWidth and content
Quantised with rangemax(1, ceil_log2(q_hi - q_lo + 1)) bits, unsigned q - q_lo
Quantised without rangesigned q: 32 bits for f32, 64 bits for f64, type width for integers
Not quantisedraw bits: bool 1, integer width, f32 32, f64 64
Enummax(1, ceil_log2(n_variants)) bits, unsigned variant index

ceil_log2(1) is 0, so a single variant uses one bit by the max(1, …) rule. An index at or above the variant count is Malformed on decode.

Strings and lists

A variable-length field starts with an unsigned 16-bit length, LSB first. A string’s length counts UTF-8 bytes; a list’s length counts elements. Elements are bit-packed with no byte alignment and use the rules of their element type; quantisation and range apply to every list element.

Empty strings and lists are valid. The encoder rejects a value longer than max_len with TooLong. The decoder rejects a wire length above max_len, an element count whose bits would overrun the frame, and invalid UTF-8 as Malformed. These checks happen before allocation or state mutation.

Non-finite values

NaN and infinities are rejected by the encoder with EncodeError::NonFinite(field_index) and leave encoder state unchanged. Custom callback predictors must also return finite predictions; check_predictor checks this property.

Predictors and tolerance

A predictor consumes samples (t, x), where t is the unwrapped tick count in nanoseconds divided by tick_ns. Wire ticks wrap at 65,536 but predictor time does not. Updating requires a strictly increasing t; reset clears the state. The polynomial predictors keep a window of samples, oldest first. ewma keeps a single smoothed level and needs no window.

Built-in predictors

KindMinimum windowBehaviour
hold_last1Returns the newest final value, or None when empty.
ewmanoneFlat exponentially weighted moving average; requires alpha.
linear2Least-squares degree-1 polynomial.
quadratic3Least-squares degree-2 polynomial.
cubic4Least-squares degree-3 polynomial.

For degree d, the polynomial fit uses m = d + 1 time-normalised moments. With window samples (t_i, x_i), it sets t0 to the oldest time and S = newest_t - t0, then uses u_i = (t_i - t0) / S. It solves the resulting m × m system by Gaussian elimination with partial pivoting, rejects pivots below 1e-12, and evaluates the result by Horner’s method at u = (t - t0) / S. All accumulation and evaluation order is fixed; there is no use of fused multiply-add.

Predictions are made for t strictly after the newest sample, so u > 1 is normal. A fit returning a non-finite result yields None.

EWMA

ewma is configured with a smoothing factor alpha, which must be finite and in (0, 1]:

predictor: { type: ewma, alpha: 0.2 }

The first sample sets the level exactly. Every later sample updates it with beta = 1 - alpha cached at construction:

level = alpha * x + beta * level

All operations are plain f64 in that order with no fused multiply-add. A larger alpha tracks new samples faster; alpha = 1 gives the same result as hold_last prediction. predict(t) returns the current level for any tick, so the forecast is flat and does not extrapolate a trend. Irregular tick spacing does not change the weighting: each accepted sample contributes equally to the recurrence. A non-finite level yields None.

The state hash covers the sample count, alpha bits, last sample tick and level bits, in that order as little-endian bytes. Both the Rust implementation and the Python reference model use this layout.

Opaque fields

bool, enum, string and list fields may only use hold_last. Their predictor stores the last final value: a slot for bool/enum, UTF-8 bytes for a string, or one slot per list element. Equality is exact; there is no tolerance. For a list this means equal length and equal elements after quantisation and casting.

Tolerance

For numeric fields, tolerance declares abs, rel, or both. With both, mode: all requires both bounds to pass and mode: any requires either. The comparison uses final f64 values:

d    = |truth - prediction|
a_ok = abs is None or d <= abs
r_ok = rel is None or d <= rel * |truth|

Tolerance is inclusive (<=). It must not be smaller than one quantise step. auto tolerance is not implemented in v1.

Recovery periods

Each predictor field may declare refresh (K) and reset (K_R) in the field or in the message sync: block. K_R must be a multiple of K. For predictors with a window, K must be at least that window; for ewma and hold_last any positive K is valid. Consecutive committed Refresh frames are exactly K apart; consecutive Reset frames are exactly K_R apart. max_resets_per_frame limits how many fields may reset in the same frame.

A Reset clears the receiver’s predictor and immediately updates it with the included true value. A Refresh only updates. Included is a normal true value that also updates both ends. See Recovery and validity for the receiver’s trust rules.

Recovery and validity

Sequence and ticks

Each frame carries an 8-bit sequence number and a 16-bit wire tick count. A decoder expects the next sequence number for each message type. A late frame is rejected as StaleFrame; a gap marks all predictor fields for that message as untrusted until a Reset is delivered.

dt == 0 is rejected as Malformed before any state mutation. A silence of exactly 65,536 wire ticks therefore aliases to zero and loses one harmlessly framed update; the next frame shows the sequence gap.

The 8-bit sequence number has a documented blind spot: losing exactly a multiple of 256 consecutive frames is not detected by sequence alone. The next Reset bounds the damage. This is the sole exception to “no silent staleness”.

Field validity

Every decoded field has one of four validity values:

ValidityMeaning
ValidThe true value was received or explicitly checked this frame.
PredictedThe receiver’s predictor supplied the value.
UnknownNo trustworthy value is available after startup or a gap.
ReSyncA Refresh disagreed with the receiver’s prediction.

Decoded::missed reports the sequence gap and Decoded::resynced reports the ReSync transition. Unknown scalar fields carry Slot(0) as a placeholder; callers must read validity before using the value.

No prediction from untrusted state

The receiver keeps a trust flag per predictor field. Startup and sequence gaps clear it. Only a Reset sets it again. An Included value updates the predictor but does not make later predictions trustworthy: on a one-way link the sender does not know that the receiver missed a frame.

Refresh compares the received true value with the receiver’s prediction on final values. A mismatch produces ReSync and the included value becomes Valid. A match keeps the field trustworthy.

Containment

The decoder parses and validates the CRC, message ID, presence bits, payload lengths, UTF-8 and enum ranges before mutating persistent state. If any check fails, predictor state and trust flags are unchanged. Only the diagnostic crc_fail_streak, stale run and last stale sequence counters may change. Fuzz targets assert this invariant around every feed call.

State hashes

state_hashes(message_index) exposes FNV-1a 64-bit hashes of each predictor’s state. Polynomial predictors hash their window in oldest-first order. For ewma, the hash covers the sample count, alpha bits, last sample tick and smoothed level bits, in that order as little-endian bytes. These hashes are a deterministic observability tool: both ends should agree after a delivered Reset, and they must not change when a frame is rejected. For opaque hold_last predictors the hash covers a presence flag and the stored slots or bytes.

Cost of the conservative rule

Marking every predictor field Unknown after a gap is conservative but not free. docs/guarantee-report.md measures the counterfactual cost if the sender knew about untrusted fields and had to send true values: about 6 bytes per committed frame on lossy profiles. The current one-way design cannot know, so wire bytes do not change when loss occurs. See Guarantees.

Guarantees

These statements are tested, not aspirational. The executable definitions live in tests/testkit/tests/guarantees.rs and the golden vectors in tests/vectors/.

GuaranteePrecise meaning
BoundEvery delivered Predicted value is within the field’s declared tolerance of the sender’s true final value, after quantisation and casting.
No silent stalenessAfter startup, a gap or a failed decode, affected fields are Unknown until re-validated. Losing exactly a multiple of 256 consecutive frames is the documented exception.
Self-stabilisationA delivered Reset makes the decoder’s predictor state equal to the encoder’s for that field.
DeterminismIdentical inputs give identical frame bytes and predictor-state hashes on every supported platform.
ContainmentA rejected frame leaves predictor state and trust unchanged; only named diagnostic counters may change.

Test envelope

The guarantee suite runs 200 seeds × 192 frames × four channel profiles: clean, 5% Bernoulli loss, 25% Bernoulli loss, and a Gilbert-Elliott burst profile. Each run includes adjacent reordering, duplication and single-bit payload corruption. The decoder uses resync_n = 1; the encoder uses K = 8, K_R = 32 and max_resets_per_frame = 8.

Gap-rule cost (counterfactual)

These numbers are not observed bandwidth. The sender has no feedback, so its frames are identical whether or not the receiver has lost data. The table estimates what a sender with feedback would spend if it sent true values instead of compact Predicted values during windows where receiver fields are untrusted.

For each delivered frame, the test adds a field’s payload cost when that field was untrusted before the frame and the frame used Predicted. It divides the total by all committed frames (200 × 192 = 38,400). In the guarantee signal, the five numeric fields and the enum each cost 1 byte, the string costs 7 bytes and the list costs 4 bytes.

Loss profileHypothetical extra bytes per committed frame
0% (clean)0.000
5% Bernoulli6.341
25% Bernoulli6.140
Burst6.042

The cost stays near 6 B/frame rather than rising with loss: more loss creates more untrusted windows but also drops frames that would contribute to them, and frequent resets truncate those windows. Reproduce it with:

cargo test -p predsync-testkit --test guarantees \
  conservative_gap_rule_extra_bytes_report -- --exact --nocapture

The other guarantees were unaffected in that run: delivered predicted values stayed in bounds, no field was predicted from untrusted state outside the exact 256-frame blind spot, delivered resets converged state hashes, rejected frames did not change them, and two identical simulations produced identical bytes.

Cross-platform determinism

pixi run qemu-determinism runs the same no-alloc scenario on the host and on a Cortex-M4 under QEMU. It compares frame bytes, decoded views and encoder/decoder state hashes, and fails if any digest differs between the two targets.

Scope limits

  • Custom C/Python predictor callbacks are outside the cross-platform bit-exactness guarantee; their floating-point behaviour is the caller’s responsibility.
  • Transport framing is a host responsibility. The protocol assumes exactly one complete frame per feed call.
  • Frames do not identify senders. Separate streams are mandatory.

API reference

predsync exposes the same protocol through four surfaces:

SurfaceGenerated referenceUse it when
Rust core and compilerRust API (rustdoc)You need the alloc API, fixed-storage API, schema compiler or generated wrappers in Rust.
Python bindingsPython API (pdoc)You are writing host code in Python.
C ABIC API (Doxygen)You need a stable C interface from C, C++ or another FFI-capable language.
Generated wrappersLanguage API referencesYou want typed message structs instead of hand-built value arrays.

Build all references with pixi run docs and open docs/site/index.html. The generated directories are not checked in; they are rebuilt from source on every docs run.

Common rules

All APIs share these rules:

  • A schema is parsed once and then shared by one encoder and one decoder. The message ID is derived from the message name and is stable across sets.
  • Use one encoder per sender and one decoder per incoming stream. Frames do not carry a sender identity.
  • now_ns is a monotonic host clock used only to advance frame ticks. The decoder never reads time.
  • Decoder::feed (or its language equivalent) accepts exactly one complete frame. Transport framing is the host’s responsibility.
  • Check per-field validity before acting on a value. Predicted is bounded but is not a fresh measurement; Unknown is not a value you should trust.

Choosing a Rust path

The Rust API has three levels:

  1. Alloc API — predsync_core::Encoder and Decoder with Value and Vec. This is the default and is what the Rust quickstart uses.
  2. Fixed-storage API — the same types with with_storage, plan_into and caller-owned buffers. See Embedded and no-alloc use.
  3. Generated wrappers — predsync_compiler::Builder emits typed enums, message structs and a PredictorSet; see Generated wrappers.

The C ABI mirrors the alloc API with opaque handles and caller-owned buffers. The Python bindings mirror it with dict/list values and generated classes.

Error handling

Error kindMeaning
EncodeError / predsync.EncodeErrorWrong field count, invalid value, non-finite scalar, time not advancing, stale plan, or output buffer too small.
DecodeError / predsync.DecodeErrorFrame too short, CRC mismatch, unknown message, malformed value, or stale frame.
C statusOk, NullPointer, InvalidSchema, InvalidHandle, BufferTooSmall, InvalidValue, EncodeError, DecodeError, or Panic; a second output carries the detailed code.

A rejected frame leaves predictor state and field trust unchanged, apart from named diagnostic counters such as the CRC-failure streak.

Rust API

The user-facing crate is predsync, a facade that re-exports the three implementation crates and provides the predsync CLI. The implementation is split into:

  • predsync-schema — schema types, message IDs and storage layouts. It is no_std and supports alloc as an optional feature.
  • predsync-core — bit packing, CRC, quantisation, predictors, encoder and decoder. It is no_std; alloc is a default feature and can be disabled.
  • predsync-compiler — YAML parsing, validation, schema-set collision checks and deterministic Rust/Python/C code generation.

All four crates share one version and pin each other exactly. The facade’s compiler feature implies std; embedded users should use default-features = false. The full item-by-item reference is here.

Schema tooling

predsync-compiler exposes the same pipeline used by the command line:

  • parse_schema(&str) parses one YAML document into a ParsedSchema, with the parsed SchemaSet and any non-fatal warnings.
  • check::check_sets(&[PathBuf]) parses a set of files or directories and checks message-ID collisions; check::render_table formats its report.
  • Builder chains .set(path) for one or more sets. .check() runs the collision checks; .generate(name) writes into Cargo’s OUT_DIR and emits rerun-if-changed directives; .generate_to(path) writes to an explicit path. .custom_predictor(name, path) registers custom predictor modules.
  • generate_rust, generate_rust_with_options, generate_python and generate_c generate source from an already parsed SchemaSet.

For simple Rust-only generation use predsync schema_build (see Command line). Keep a build.rs when you need custom predictor registration or generated Python/C source.

Alloc API

#![allow(unused)]
fn main() {
use predsync::{parse_schema, Decoder, DecoderConfig, Encoder, EncoderConfig, Slot, Value};

let set = parse_schema(SCHEMA).unwrap().set;
let mut encoder = Encoder::new(&set, 0, EncoderConfig::default()).unwrap();
let mut decoder = Decoder::new(&set, DecoderConfig { resync_n: 1 }).unwrap();

for tick in 0..3u64 {
    let values = [Value::Scalar(Slot::from_f64(1.25))];
    let plan = encoder.plan(&values, tick * 1_000_000).unwrap();
    let mut frame = vec![0u8; plan.len];
    let info = encoder.commit(plan, &mut frame).unwrap();
    frame.truncate(info.len);

    let decoded = decoder.feed(&frame).unwrap();
    assert_eq!(decoded.fields[0].value, values[0]);
}
}

plan is pure; commit advances encoder state. encode combines the two when you do not need to inspect the plan. The output buffer must be at least plan.len bytes, but the frame may be shorter; slice it with info.len.

Encoder::new and Decoder::new validate the schema and configuration once. Encoder::with_registry and Decoder::with_registry add runtime custom predictors; the registry is borrowed for the lifetime of the engine.

Predictors

predsync_core::predictor exports HoldLastPredictor, EwmaPredictor and the LinearPredictor, QuadraticPredictor and CubicPredictor wrappers. All implement the Predictor trait (update, predict, reset, state_hash). EwmaPredictor::new(alpha) takes a finite alpha in (0, 1] and produces a flat smoothed forecast after the first sample; alpha = 1 matches hold-last behaviour. See Predictors and tolerance for the wire-level rules.

Decoded output

Decoded contains:

  • message_index — the selected message in the schema set;
  • fields — one FieldOut per field, with validity and value;
  • missed — frames lost since the previous accepted frame;
  • resynced — whether a refresh disagreed with receiver prediction.

Validity is Valid, Predicted, Unknown or ReSync. Unknown fields have a placeholder value that must not be used as a measurement.

Fixed storage

For no_std or allocation-free hosts, use Encoder::with_storage, Decoder::with_storage, plan_into and decode_into. The compiler emits SCHEMA_REF and STORAGE_LAYOUT constants so buffer sizes are derived from the schema instead of guessed. See Embedded and no-alloc use and the borrowed-storage test in examples/generated_example/tests/generated.rs.

Generated wrappers

predsync_compiler::Builder writes a Rust module with:

  • namespace and message modules;
  • ID and FIELD_* constants;
  • one enum per schema enum with index() and from_index();
  • a struct with alloc::String / alloc::Vec<T> fields;
  • to_values() and from_values(&[Value]) -> Option<Self>;
  • SCHEMA_REF, STORAGE_LAYOUT and a generated PredictorSet.

from_values returns None for a wrong field count, wrong value kind or an out-of-range enum index. The generated module depends only on predsync_core and alloc. See Generated wrappers.

Doctests

pixi run docs-doctests compiles and runs the public examples in the crate documentation. They cover schema parsing, encoding, decoding and generated wrapper use.

Python API

The Python extension is built with PyO3 and published as an abi3 wheel for CPython 3.10 and newer. The complete generated reference is here.

Encoder and decoder

The wheel does not bundle schema YAML. Load a schema from a file path in your project; this example uses the checked-in demo schema from a source checkout.

from pathlib import Path

import predsync
from predsync.generated import Telemetry, TelemetryMode

schema_yaml = Path("examples/generated_example/schema/telemetry.yaml").read_text()
sample = Telemetry(
    x=1.25,
    mode=TelemetryMode.Active,
    label="nominal",
    samples=[7, 8, 9],
)

encoder = predsync.Encoder(schema_yaml, message=Telemetry.message_index, tick_ns=1_000_000)
decoder = predsync.Decoder(schema_yaml, message=Telemetry.message_index, resync_n=1)

for tick in range(3):
    frame, info = encoder.encode(sample.to_values(), tick * 1_000_000)
    decoded = decoder.feed(frame)
    assert Telemetry.from_values(decoded.values()) == sample

Encoder.encode accepts either a field-name dict or a schema-order list. Enums cross the boundary as variant names. The returned info dict has len, n_predicted, n_included, n_refresh, n_reset and bound_applies.

DecodedFrame exposes message_index, missed, resynced, fields and values(). Each entry in fields has validity and value; check validity before using a predicted value.

EncodeError and DecodeError carry a kind string such as Malformed, BadCrc, UnknownMessageId or StaleFrame.

Generated classes

predsync.generated is installed when the package is imported. It exposes the four-field demo Telemetry and its TelemetryMode enum. Continuing the example above:

restored = Telemetry.from_values(decoded.values())
assert restored == sample

Generated classes carry schema_yaml, message_index and field_names, so they can construct an Encoder or Decoder without a second schema copy. from_values raises ValueError for an incompatible value list.

Custom predictors

Registry holds Python callables with reset, update, predict and state_hash methods. register_model_checked also verifies a saved trace against the model before registration. Create engines with encoder_with_registry or decoder_with_registry; a plain Encoder or Decoder never sees the registry.

Encoder, decoder and registry objects are unsendable. Use one per thread, or keep them on a single-threaded executor such as the default ROS 2 executor. Do not share one decoder between several publishers; the message ID identifies a message type, not a sender.

Type stubs

The wheel ships py.typed and predsync.pyi, so type checkers see typed signatures for the native module. Generated classes are plain Python classes and are checked from their emitted source.

C API

The C ABI is declared in crates/ffi/include/predsync.h. The complete generated reference is here. Regenerate the header with pixi run c-header; pixi run c-header-check fails if it is stale.

Handle and status model

Every entry point returns a PredsyncStatus. Ok means success; other values are NullPointer, InvalidSchema, InvalidHandle, BufferTooSmall, InvalidValue, EncodeError, DecodeError and Panic. Encode and decode functions also write a detailed error code into a caller-provided uint32_t.

All objects are opaque handles:

  • PredsyncSet owns a parsed schema set.
  • PredsyncEncoder and PredsyncDecoder own one engine each.
  • PredsyncDecoded owns one decoded frame until freed.
  • PredsyncRegistry owns custom predictor callbacks.

Free handles in reverse order with predsync_set_free, predsync_encoder_free, predsync_decoder_free, predsync_decoded_free and predsync_registry_free. No function takes ownership of caller memory.

Values

A PredsyncValue is a tagged union represented as a plain struct:

FieldMeaning
kindScalar, Str or List.
elementScalar type of a scalar or list element, including Enum for a variant index.
scalarEight-byte slot bits for a scalar.
ptrBorrowed bytes for a string or slot bits for a list.
lenByte count for a string, element count for a list.
capCapacity of caller-owned decode storage.

On encode, ptr is borrowed for the duration of predsync_encode. On decode, set cap to your buffer capacity; the library returns BufferTooSmall rather than writing past it.

Minimal sequence

PredsyncSet *set = NULL;
PredsyncEncoder *encoder = NULL;
uint8_t frame[256];
uintptr_t frame_len = 0;
uint32_t error = 0;
PredsyncEncodeInfo info;

if (predsync_set_from_yaml(yaml, yaml_len, &set) != Ok) { /* handle error */ }
if (predsync_encoder_new(set, 0, 1'000'000ULL, 0xffffu, &encoder) != Ok) { /* ... */ }
if (predsync_encode(encoder, values, field_count, now_ns,
                    frame, sizeof(frame), &frame_len, &info, &error) != Ok) { /* ... */ }

0xffff for max_resets_per_frame selects the library default. The frame bytes are the first frame_len entries of frame; pass exactly that slice to predsync_decode_feed.

A complete program is in examples/c/quickstart.c. It is compiled with -Wall -Wextra -Werror and run by pixi run c-abi.

Generated typed wrappers

For demo schemas, the compiler also emits demo_telemetry_pack, demo_telemetry_unpack, DemoTelemetry and DemoTelemetryMode. The pack helper writes into caller-owned PredsyncValue storage and a scratch word array; the unpack helper fills a fixed-capacity struct. These wrappers are generated from the same schema as the Rust and Python classes.

Safety notes

C callbacks for custom predictors must be deterministic and must not call back into the encoder or decoder. The FFI layer catches Rust panics and returns Panic, but a callback that mutates shared state from another thread is still a caller error. Each entry point documents its preconditions in the header.

Embedded and no-alloc use

predsync-core and predsync-schema are no_std. The default alloc feature can be disabled, and every hot path has a caller-storage variant that performs no steady-state allocation.

Feature flags

CrateFeatureEffect
predsync-schemaalloc (default)Enables owned String and Vec schema types.
predsync-corealloc (default)Enables Value, Plan, managed owned slices and Encoder::new.
predsync-corestdEmpty marker for hosts that also link std.
predsync-coretest-supportEnables test-only helpers.

A true no-alloc firmware build uses:

predsync-core = { path = "../../crates/core", default-features = false }
predsync-schema = { path = "../../crates/schema", default-features = false }

The compiler is std-only and is intended for build scripts or offline tooling, not firmware.

Caller storage

The no-alloc API passes all scratch buffers explicitly:

  • EncoderStorage::borrowed(...) for field metadata and predictor state;
  • DecoderStorage / DecoderMessageStorage::borrowed(...) for decode state;
  • plan_into(&[ValueRef], now_ns, &mut PlanBuf) instead of plan;
  • decoder.decode_into(&frame, &mut ParsedBuf, &mut DecodedBufStorage) or the staged parse_into / apply_into path.

predsync_compiler::Builder emits SCHEMA_REF and STORAGE_LAYOUT constants. Use predsync_core::storage::try_required_storage with that layout to size buffers at compile time. examples/generated_example/tests/generated.rs shows the whole borrowed path, and tests/qemu/scenario is the shared no-alloc scenario used by the determinism check.

Values without allocation

ValueRef borrows scalars, lists and strings. BoundedValue<MAX_LIST, MAX_STR> owns inline heapless::Vec / String storage for hosts that need an owned value but cannot use a global allocator. Both convert with as_ref() so the same encoder logic serves alloc and no-alloc callers.

Custom predictors in firmware

A custom predictor is selected by name in the schema. Link-time registration uses the Predictor and PredictorBuilder traits; runtime registries require alloc and are aimed at hosts. A generated PredictorSet implements both traits for the predictors declared in a schema.

Custom callbacks are outside the cross-platform bit-exactness guarantee when they use floating point. Keep them deterministic on the target.

Framing and concurrency

The decoder expects exactly one complete frame per call. A UART, CAN or USB stream needs a host framing layer; the serial/COBS example is a small allocation-free implementation. Do not concatenate frames or feed partial buffers.

There is no global state and no internal locking. Use one encoder per sender and one decoder per incoming stream. On a single-core firmware this is usually one of each per periodic task.

Cross-builds

The CI tasks cross-build the no-alloc paths for thumbv7em-none-eabihf:

pixi run embedded-build
pixi run schema-embedded-build
pixi run generated-embedded-build
pixi run serial-cobs-embedded-build
pixi run qemu-determinism

qemu-determinism runs the same scenario on the host and under QEMU and compares frame bytes, decoded views and predictor-state hashes.

Examples

Examples are host programs, not part of the library. They show how to own the transport while keeping predsync responsible for bytes and predictor state.

  • Generated wrappers — typed Rust structs built at compile time.
  • UDP — datagram transport with a deterministic loopback self-test.
  • Python UDP — generated Python wrappers, lossy-link recovery and Ctrl-C encode statistics.
  • Serial and COBS — byte-stream framing with a COBS delimiter.
  • ROS 2 — r2r publisher/subscriber with best-effort QoS.
  • C quickstart — minimal C ABI encode/decode sequence.

The long-running senders (UDP, Python UDP, serial/COBS and the ROS 2 talker) print Ctrl-C summaries with predicted fields, byte savings, percentage size reduction and message sizes.

All examples use the same telemetry schema: a quantised linear-predicted numeric field, a hold_last enum, a hold_last string and an always-included list.

The host must supply framing and buffering. predsync does not scan byte streams for frames, retransmit, or infer a sender from a message ID.

Generated wrappers

The compiler generates typed wrappers from a schema, so application code does not hand-build Value arrays. For a simple Rust-only project, generate the module once with the CLI instead of adding a build script:

predsync schema_build --set schema/telemetry.yaml --out src/telemetry.rs

Or, from a source checkout:

pixi run schema-build --set schema/telemetry.yaml --out src/telemetry.rs

Use a build script when you need Cargo to regenerate the module when schemas change, or when you register custom predictors:

fn main() {
    predsync_compiler::Builder::new()
        .set("schema/telemetry.yaml")
        .generate("telemetry.rs")
        .expect("generate telemetry wrappers");
}

Builder::generate emits rerun-if-changed directives for every schema file.

Include the generated file in a module:

#![allow(unused)]
fn main() {
include!(concat!(env!("OUT_DIR"), "/telemetry.rs"));
}

The generated Rust module exposes:

  • namespace and message modules;
  • ID and FIELD_* constants;
  • one Rust enum per schema enum, with index() and from_index();
  • a struct with alloc::String/alloc::Vec<T> fields;
  • to_values() and from_values(&[Value]) -> Option<Self>;
  • SCHEMA_REF and STORAGE_LAYOUT for fixed-storage callers;
  • a generated PredictorSet implementing the public predictor traits.

The wrappers depend only on predsync_core and alloc; they never mention std. from_values returns None for the wrong field count, wrong value kind or an out-of-range enum index. Generation re-runs the message-ID checks, so a colliding schema set fails the build before emitting code.

Generated Python and C wrappers follow the same schema. Python emits enum and message classes with to_values/from_values; C emits fixed-capacity structs plus *_pack and *_unpack helpers that take caller-owned scratch buffers. The schema_build command writes Rust modules only; use generate_python or generate_c from predsync_compiler for the other languages.

The working example is examples/generated_example/; its tests exercise both the alloc API and borrowed fixed storage.

UDP example

examples/udp/ is a small Rust host that uses std::net::UdpSocket. It shows the intended division of labour: UDP provides datagrams, predsync provides the frame.

# deterministic CI-friendly self-test on loopback
cargo run -p predsync-udp-example -- self-test

# send frames to a receiver
cargo run -p predsync-udp-example -- send 127.0.0.1:9000 10

# receive frames from a local port
cargo run -p predsync-udp-example -- receive 127.0.0.1:9000 10

The schema is parsed at runtime with predsync_compiler::parse_schema, using a schema embedded in the example crate. Both sides therefore use the same field order and predictor configuration.

The self-test mode binds two loopback sockets, encodes a deterministic telemetry sequence, sends each frame as one datagram, feeds it to a fresh decoder and asserts the decoded values. It needs no external network and is the mode run by pixi run examples.

send installs a SIGINT handler so Ctrl-C stops the loop and prints an encode summary. The same summary is printed when the requested frame count finishes. It reports median, mean and a 95% bootstrap confidence interval for predicted fields per frame, byte savings and percentage size reduction. A maximum/mean message-size line precedes the overall figure. The baseline is a fresh encoder at the same tick, so the savings are the cost of sending every true value every time.

Notes for real deployments:

  • Use one Decoder per remote sender; a UDP socket may receive from many peers.
  • Check Decoded::fields[*].validity before acting on a predicted value.
  • UDP can reorder or duplicate datagrams. Sequence handling only covers frames that reach the decoder; it does not request retransmission.
  • Keep datagrams below the path MTU. The example uses a 1500-byte receive buffer.

Python UDP example

examples/python/ is a standalone host for the Python bindings. It uses a one-way UDP link: the sender owns the socket, while predsync owns frame bytes and receiver-side trust.

Build the extension and run the deterministic path from the repository root:

pixi run python-build
python examples/python/telemetry_udp.py self-test

self-test uses an in-memory link that drops every eighth frame. It verifies that a sequence gap marks predictor fields Unknown, and that later delivered values plus staggered periodic Reset frames restore usable values. No network access is required.

Sender and receiver

For a real loopback, start the receiver first:

python examples/python/telemetry_udp.py receive 127.0.0.1:9000 1000
python examples/python/telemetry_udp.py send 127.0.0.1:9000 1000

The sender creates one Encoder and sends one frame per datagram. The receiver keeps a separate Decoder for each source address, because the message ID selects a message type rather than a sender:

decoder = decoders.setdefault(
    peer,
    predsync.Decoder(
        Telemetry.schema_yaml,
        message=Telemetry.message_index,
        resync_n=1,
    ),
)
decoded = decoder.feed(frame)

Each datagram is exactly one predsync frame, so no extra framing is needed. Check decoded.fields before trusting predicted values; decoded.missed and decoded.resynced report loss and recovery.

Ctrl-C statistics

Press Ctrl-C in the sender (or let the frame count complete) to print mean, median and a 95% confidence interval for three numbers:

  • fields predicted per frame, from info["n_predicted"];
  • byte savings per frame relative to a fresh encoder carrying the same sample and tick, i.e. the cost of sending every true value every time;
  • the same saving as a percentage of the baseline frame size.

A line with maximum and mean message size precedes an overall percentage reduction across all encoded frames. The interval is a seeded bootstrap percentile interval of the mean, so the output is reproducible. It describes the frames the sender encoded; predsync has no back channel, so the sender cannot know which frames the receiver saw.

Serial and COBS example

examples/serial_cobs/ shows how to carry predsync frames over a byte stream. Serial ports have no message boundaries, so the host adds COBS framing with a 0x00 delimiter. COBS removes zero bytes from the payload and guarantees that the delimiter occurs only between frames.

# deterministic in-memory round trip (CI gate)
cargo run -p predsync-serial-cobs-example -- self-test

# optional real port on a POSIX host (configured with stty)
cargo run -p predsync-serial-cobs-example -- send /dev/ttyUSB0 115200 10
cargo run -p predsync-serial-cobs-example -- receive /dev/ttyUSB0 115200 10

The in-memory test encodes predsync frames, applies COBS, appends the delimiter, decodes COBS, and feeds the recovered frame to the predsync decoder. The result must match the direct frame byte-for-byte and decode to the same values. Unit tests cover zero-byte handling, empty payloads, delimiter placement, truncation and malformed codes.

The real-port mode is optional because CI agents do not have a serial device and platform support varies. It opens the port with the requested baud rate, accumulates bytes until a delimiter, COBS-decodes one frame at a time, and prints decoded values with their validity flags. Its sender stops on Ctrl-C and prints median, mean and a 95% bootstrap confidence interval for predicted fields, byte savings and percentage size reduction. A maximum/mean message-size line precedes the overall figure. Savings are measured on predsync frame bytes before COBS framing; the baseline is a fresh encoder sending every true value at the same tick.

Framing is not part of the predsync wire format. A receiver must pass exactly one complete frame to Decoder::feed; never concatenate frames or feed a partial buffer.

ROS 2 example

examples/ros2/ uses r2r Rust nodes to carry predsync frames over a best-effort topic. The nodes use the Rust core and generated telemetry wrappers; ROS 2 owns only the transport.

# codec self-test; does not require ROS 2
pixi run examples-ros2

# with a supported ROS 2 installation sourced
source /opt/ros/jazzy/setup.bash
pixi run examples-ros2-build
cargo run --manifest-path examples/ros2/Cargo.toml --features ros2 --bin talker
# in another shell
cargo run --manifest-path examples/ros2/Cargo.toml --features ros2 --bin listener

r2r builds Rust message types from the sourced ROS 2 installation, so no colcon package is needed. The example limits generation to std_msgs with IDL_PACKAGE_FILTER. The ros2 feature enables the r2r dependencies; the default feature set keeps the codec library testable without ROS 2.

The codec helper (examples/ros2/src/lib.rs) owns one encoder and one decoder, converts between generated Rust values and byte payloads, and is tested by round-tripping three frames and dropping a rejected frame.

The nodes publish and subscribe std_msgs.msg.UInt8MultiArray with:

  • BestEffort reliability;
  • volatile durability;
  • a queue depth of 5.

Best effort is appropriate because predsync already handles loss and does not benefit from ROS 2 retransmission. Each message contains exactly one predsync frame; Decoder::feed is never asked to find boundaries inside a stream.

The talker stops on Ctrl-C and prints median, mean and a 95% bootstrap confidence interval for predicted fields per frame, byte savings and percentage size reduction. A maximum/mean message-size line precedes the overall figure. The baseline is a fresh encoder at the same tick, i.e. the cost of sending every true value every time.

If you have several publishers, create one decoder per publisher topic or include a sender identity in your own message wrapper. The message ID in a predsync frame identifies a message type, not a sender.

C quickstart example

examples/c/quickstart.c is a complete C11 program that:

  1. parses a schema from UTF-8 YAML into a PredsyncSet;
  2. constructs an Encoder for message 0;
  3. prepares one PredsyncValue per field;
  4. encodes a frame into a caller-owned byte array;
  5. constructs a Decoder, feeds the frame, and reads decoded metadata;
  6. frees every handle in reverse order.

The program is compiled by the C ABI harness with -Wall -Wextra -Werror, so the example cannot silently drift from the header. It is also run as part of pixi run c-abi and therefore pixi run check.

pixi run c-abi

The example deliberately uses only the generated public header. It does not include internal Rust headers or link directly to compiler internals.

For variable-length fields, PredsyncValue::ptr is borrowed on encode and must remain valid for the duration of predsync_encode. On decode, set cap to the capacity of your own buffer; the library reports BufferTooSmall rather than writing beyond it. See the C API reference.

Testing

The repository treats golden vectors and the Python reference model as the definition of correct behaviour. Rust, C and Python implementations must all replay the same scenarios.

One command

pixi run check     # run every local check
pixi run ci        # check plus the 60-second fuzz stage

The individual tasks are documented in Development and release.

Layers

LayerCommandWhat it proves
Formatting and lintpixi run fmt, pixi run clippyWorkspace, fuzz crate and standalone ROS 2 example are clean under -D warnings.
Rust unit and integration testspixi run testPrimitives, predictors, schema validation, encoder, decoder, codegen, C header shape.
Doctestspixi run docs-doctestsPublic Rust examples compile and run.
Golden vectorspixi run test / pixi run differentialAll 21 scenario vectors, 8 predictor traces and the manifest are replayed.
Differential tracespixi run differential-fullAll 10,000 fixed-seed traces are regenerated and hash-checked against the manifest.
Reference modelpixi run reference-tests, pixi run reference-modelStdlib Python oracle agrees with committed vectors.
C ABIpixi run c-header-check, pixi run c-abiHeader is current; C replays every vector with -Werror.
Python bindingspixi run python-testsPyO3 extension replays vectors and round-trips generated classes.
Embeddedpixi run embedded-build, pixi run no-alloc-entry-tests, pixi run no-alloc-stack-usageTrue no-alloc thumb build, zero steady-state allocations, recorded stack usage.
Determinismpixi run qemu-determinismHost and Cortex-M4 hashes agree.
Fuzzingpixi run fuzz, pixi run fuzz-acceptance60-second gate and 30-minute acceptance run on the 12-hour timer.
Examplespixi run examplesUDP, serial/COBS and ROS 2 codec self-tests pass.
Docspixi run docsBook, rustdoc, pdoc, Doxygen, site assembly and local link checks pass.

Golden vectors

tests/vectors/*.json contains hand-checked encoder/decoder scenarios, predictor traces, width cases, CRC/message-ID checks and a stale-frame case. Each scenario records schema YAML, operations, expected bytes and decoded output. Five diff_seed_*.json files are human-reviewed differential scenarios. traces.manifest.json records the generator version, seed range, frame count and SHA-256 of 10,000 generated traces; those traces are not committed.

Fuzzing

tests/fuzz is a standalone Cargo workspace with three libFuzzer targets: decoder_feed, schema_parse and yaml_to_schema. tools/run_fuzz.py supplies sanitizer-coverage flags on stable Rust, copies the 14-file seed corpus to a temporary directory, and stores crashes in a gitignored directory. The decoder target asserts that state_hashes(0) is unchanged whenever feed returns Err.

Reproducing a failure

Every runner names the failing vector, seed and step. For byte mismatches the message includes the first differing byte; for decoded values it names the field. Start with pixi run test, then narrow with the task from the table above. Do not regenerate golden vectors unless the wire contract itself changes.

Development and release

The development environment is defined by pixi.toml and pixi.lock. All commands below run from the repository root through pixi run.

Everyday tasks

TaskPurpose
fmt / fmt-fixCheck or apply rustfmt to the workspace, fuzz crate and standalone ROS 2 example.
clippyLint every workspace target and the ROS 2 codec example with -D warnings.
test / testsRun the full Rust workspace test suite.
buildBuild all workspace crates.
docsBuild the book, API references and site, run doctests and check local links.
schema-checkValidate schema sets and print the message-ID table.
schema-buildGenerate a Rust wrapper module from schema sets without a build.rs.
rust-targetsInstall the pinned embedded std targets into the pixi Rust sysroot.
examplesBuild and run all deterministic example self-tests, including the ROS 2 codec.
examples-ros2-buildBuild the r2r nodes; requires a sourced ROS 2 installation.
checkEvery local check, including docs and examples.
cicheck plus the 60-second fuzz stage.
wheelsClean dist/, build the sdist and the x86_64/aarch64 manylinux wheels.
c-release-archiveBuild the C header/static/shared-library release tarball.
release-checkVerify the exact tag, workspace version, changelog and artefacts.
publish-dry-runPackage all publishable crates and verify the wheel and sdist.

Specialised tasks cover golden vectors, the Python reference model, C ABI, Python bindings, embedded cross-builds, QEMU determinism and fuzzing. The Testing chapter lists them in the order used by CI.

CI requirements

GitHub Actions uses prefix-dev/setup-pixi with the committed pixi.lock, so the pinned Rust toolchain, rustfmt, clippy, C++ compiler, Python, maturin and documentation tools are installed automatically. The rust-targets task downloads the matching Rust 1.100.0 standard libraries for thumbv7em-none-eabi, thumbv7em-none-eabihf and aarch64-unknown-linux-gnu into the pixi sysroot. qemu-system-arm is installed in the workflow before the QEMU task. The README build badge links to the GitHub Actions CI workflow.

Documentation build

pixi run docs performs these steps:

  1. docs-doctests compiles and runs public Rust examples.
  2. docs-book builds the mdBook into docs/book/book/.
  3. docs-rust runs rustdoc with warnings denied into target/doc/.
  4. docs-python uses pdoc on the installed extension into docs/site/api/python/.
  5. docs-c runs Doxygen over the generated C header into docs/site/api/c/html/ and fails if the generated pages omit public C symbols.
  6. docs-site copies the book and rustdoc output into docs/site/ and writes the landing page.
  7. docs-links runs lychee --offline --include-fragments over the sources and generated site.

All generated documentation is gitignored. Link checking is local: a docs build never requires network access. External URL checks are deferred to a stage on the 12-hour timer.

On every v* tag push, the documentation workflow runs pixi run docs and publishes the generated docs/site/ to https://predsync.tgodfrey.com/ with GitHub Pages, so the live site matches the released version. The github-pages environment must allow v* tag deployments; configure that in the repository’s environment protection rules. Cloudflare redirects the exact root path to https://predsync.tgodfrey.com/book/index.html with a 301. The generated root page also carries a client-side redirect and direct links to the Rust API, the Python API and the C API as a fallback. The canonical documentation URL remains the book.

The Cloudflare rule is configured outside the generated site. With CLOUDFLARE_API_TOKEN (Zone > Single Redirect > Edit) and CLOUDFLARE_ZONE_ID set, run pixi run docs-cloudflare-redirect to create or update it. The rule matches http.host eq "predsync.tgodfrey.com" and http.request.uri.path eq "/", then redirects to https://predsync.tgodfrey.com/book/index.html with status 301 and query strings not preserved. Matching only / avoids a loop with the book and API paths. The equivalent dashboard rule is a Redirect Rule with the same expression and target.

Release metadata

The root README.md, LICENSE and CHANGELOG.md are the public release front door. The crates.io set is predsync-schema, predsync-core, predsync-compiler and the predsync facade. Those four crates pin each other with exact versions so a facade release cannot resolve against an incompatible compiler or core. predsync-ffi, predsync-py, the test crates and the example crates are publish = false.

The Python distribution is also called predsync. Its version is dynamic and comes from [workspace.package] version; Cargo’s 0.1.0-rc.1 becomes PyPI’s 0.1.0rc1. Each publishable crate carries a copy of LICENSE so the licence text appears in the crate archive and on crates.io.

Local version bumps

Install the release helper once:

cargo install cargo-release --locked

release.toml makes cargo-release update versions and the changelog, create one commit and one vX.Y.Z tag, and push them. It never publishes to a registry. The current development version is lower than the first release candidate, so the first tag is explicit:

cargo release 0.1.0-rc.1 -x --no-publish

After the release candidate has been smoke-tested, promote it with:

cargo release release -x --no-publish

cargo release rc is deliberately not used: from 0.1.0-alpha.1 it would produce 0.1.1-rc.1, not 0.1.0-rc.1. The facade crate owns the single workspace tag and the CHANGELOG.md replacement, so a workspace release has one tag rather than one tag per crate.

Publishing dry runs

pixi run publish-dry-run

The dry-run tool:

  • lists each publishable Cargo crate with cargo package --list and requires Cargo.toml, README.md and LICENSE;
  • runs cargo publish --workspace --dry-run;
  • builds a Python wheel and sdist into a temporary directory;
  • installs the sdist in a clean virtualenv from a directory containing no repository checkout, proving the path-dependent workspace crates are in it;
  • never uploads anything.

The scheduled GitHub Actions workflow runs publish-dry-run every 12 hours. Tag builds run the same checks in release-verify before any upload.

Tag-driven release

The release workflow is .github/workflows/release.yml. It runs only on v* tag pushes, so ordinary branch and pull-request builds can never publish.

The workflow performs:

  1. verify — release-check requires an exact tag at HEAD, a clean tree, TAG_NAME == v$(workspace version) and a matching changelog heading. It then runs ci and publish-dry-run.
  2. build-wheels — builds the sdist plus the x86_64 and aarch64 manylinux2014 wheels in clean containers.
  3. build-c-archive — builds the C header, static library and shared library tarball.
  4. publish — waits at the protected GitHub release environment for manual approval. Credentials are bound only inside this job. publish_crates.py checks crates.io for each crate/version, waits for dependencies to become indexed, skips versions already published and publishes the rest in dependency order. publish_pypi.py uploads only the expected wheels and sdist with maturin upload --skip-existing.

Configure the repository before the first release:

  • add repository secrets CARGO_REGISTRY_TOKEN and MATURIN_PYPI_TOKEN;
  • create a GitHub Environment named release;
  • add required reviewers to that environment;
  • optionally protect v* tags.

The first upload needs temporary broad tokens because project-scoped tokens cannot be created before the crate or project exists. Rotate to scoped tokens after the release candidate is live. Duplicate crate versions fail loudly; PyPI uploads can be retried safely.

Scheduled maintenance

.github/workflows/scheduled.yml runs the 30-minute fuzz acceptance stage, the full differential trace set and the publishing dry run every 12 hours.

C release archive and documentation

Every tag build archives predsync.h, the static library, the shared library, the README and the licence as predsync-c-X.Y.Z.tar.gz. The GitHub Actions documentation workflow publishes on v* tags only, so the book and API pages match the released version. The docs task fails if Doxygen output omits public C symbols.

Before tagging a release

  1. Run pixi run ci and confirm the 60-second fuzz stage is clean.
  2. Run the timer-only stages if the change affects the wire format or predictors.
  3. Run pixi run docs and inspect docs/site/index.html.
  4. Confirm CHANGELOG.md names every user-visible change under Unreleased.
  5. Confirm generated files are current: pixi run c-header-check.
  6. Run pixi run publish-dry-run and pixi run wheels.
  7. Create the tag with cargo release, push it, and wait for the GitHub Actions release environment approval gate. Smoke-test the release candidate wheels before approving the final 0.1.0 release.