MicroRTI architecture

MicroRTI is an implementation of HLA 4 in Rust (IEEE Std 1516-2025 Framework and Rules, 1516.1-2025 Federate Interface Specification, 1516.2-2025 Object Model Template): a Run-Time Infrastructure (RTI) server and a federate client library that talk to each other over the standard HLA Federate Protocol (clause 12.13 of IEEE 1516.1).

This document is the contract between the crates. Change it only together with the code it describes.

flowchart TB
  subgraph federate["Federate process"]
    code["<b>Federate code</b><br/>Rust, or Python via microrti-python"]
    client["<b>microrti-client</b><br/>RtiAmbassador: one method per service<br/>FederateAmbassador: one per callback"]
    fedprolink["<b>FedProLink</b>, default feature<br/>a microrti-fedpro session, with resume"]
    embedded["<b>EmbeddedRti</b>, feature embedded<br/>microrti-engine inside the federate"]
    code --> client
    client --> fedprolink
    client --> embedded
  end
  other["<b>Any other HLA 4 federate</b><br/>a Federate Protocol client, any language"]
  subgraph server["RTI server process"]
    listeners["<b>microrti-fedpro</b>, RTI role<br/>listeners, framing, heartbeats, session resume"]
    service["<b>microrti</b><br/>RID, one lock around the engine,<br/>ordered callback flush, tick thread"]
    engine["<b>microrti-engine</b><br/>Rti::call(CallRequest) → CallResponse<br/>Rti::take_callbacks → CallbackRequest<br/>deterministic: no I/O, no clock"]
    listeners --> service --> engine
  end
  fedprolink <-->|"HLA Federate Protocol<br/>TCP, TLS, WebSocket, WSS"| listeners
  other -->|"Federate Protocol"| listeners
  subgraph base["Base crates"]
    proto["<b>microrti-proto</b><br/>Federate Protocol messages"]
    core["<b>microrti-core</b><br/>exceptions, logical time"]
    fom["<b>microrti-fom</b><br/>FOM modules, merged FDD"]
    encoding["<b>microrti-encoding</b><br/>HLA data encoding"]
  end
  engine ~~~ proto & core & fom & encoding
  classDef core stroke-width:2.5px
  class engine core

1. Reference material (local, outside this repository)

WhatWhere
Standard text, one file per clause../spec/text/*.txt (index: spec/INDEX.md)
Standard text, one file per PDF page../spec/pages/pNNN.txt
Figures / state chartscd ../spec && uv run --quiet --with pymupdf python render_page.py <pdf page>... writes spec/png/pNNN.png
Official Java, C++ APIs../spec/api/java, ../spec/api/cpp
Official protobuf filesproto/ in this repository
Standard MIM, XSD schemas, Restaurant sample FOMfom/ in this repository
Earlier research notes (public sources only)../microhla.org/research/*.md and *.json

The standard text is a licensed copy: never copy its prose into this repository (code, comments, docs or tests). Refer to it by clause number (“see 8.8”). Names of services, arguments, exceptions and enumerators are facts and are used as is. The API files, protobuf files, MIM and sample FOMs carry a royalty-free IEEE licence (see NOTICE).

2. Crates

microrti-proto     prost types generated from proto/*.proto (CallRequest, CallResponse, CallbackRequest...)
microrti-core      ExceptionKind / RtiError, LogicalTime / LogicalTimeInterval / TimeKind, default ports
microrti-encoding  HLA data encoding helpers (basic types, arrays, records, variant records)
microrti-fom       FOM module parser (OMT DIF XML), module merging, merged FDD model, FDD writer;
                   with the feature `url-reader`, the reader of modules named by file/http/https URL
microrti-fedpro    Federate Protocol: framing, session layer (both roles), transports TCP/TLS/WS/WSS
microrti-engine    the RTI itself: a synchronous, deterministic state machine, no I/O
microrti    binary `microrti`: hosts the engine behind Federate Protocol listeners
microrti-client    federate side: RtiAmbassador + FederateAmbassador in Rust
microrti-cli       the operator tool microrti-cli and its library (connection options, FOM codec, observer)
microrti-examples  example federates (chat, restaurant), the interoperability scenario; uses microrti-cli's library

Dependency direction (no cycles): proto <- core <- {encoding, fom} <- engine <- server and core <- fedpro <- server: the engine does not depend on the Federate Protocol crate. client depends on proto and core, on fedpro with its default feature fedpro, and on engine and fom (feature url-reader) with the optional feature embedded. It does not depend on encoding, uses fom only to read the FOM modules named by URL for its embedded RTI, and re-exports neither (it re-exports proto): a federate that encodes values with them or reads FOM modules depends on them itself, as microrti-cli does; microrti-examples depends on microrti-cli for its library. fom reaches the network (ureq, rustls) only with its feature url-reader, which the server and the embedded RTI enable and the engine does not. encoding depends on fom only with its optional feature fom (module microrti_encoding::fom: the FOM-driven codec FomCodec and its Value tree, used for MOM values and by tools).

3. The protobuf messages are the service contract

Every federate-initiated service of clauses 4 to 10 is one CallRequest alternative with one CallResponse alternative; every RTI-initiated service is one CallbackRequest alternative. The engine consumes and produces exactly these messages, the Federate Protocol carries them unchanged, and the client maps its typed Rust API onto them. There is no second, parallel request model.

Exceptions travel as ExceptionData { exception_name, details }; exception_name is the standard exception name (microrti_core::ExceptionKind::name).

Handles on the wire

Handles are opaque bytes for federates. The engine encodes its handles big-endian with a fixed width:

HandleEngine typeWire
federate, object class, attribute, interaction class, parameter, dimension, transportation typeu324 bytes
object instance, region, message retractionu648 bytes

Class, attribute, parameter, dimension, transportation type and update rate handles are the indices of the merged FDD (microrti-fom), which is append-only: joining with additional FOM modules never changes an existing handle, and the same modules loaded in the same order always give the same handles (12.2). An attribute has one handle for the class that declares it and all its subclasses; the same holds for parameters. A byte string of the wrong length or an unknown value is answered with the matching Invalid...Handle (or ...NotDefined / ...NotKnown) exception, as the service clause requires.

The client never interprets handle bytes: it must work against any HLA 4 RTI.

Logical time on the wire

LogicalTime.data and LogicalTimeInterval.data are the 8-byte big-endian encodings of microrti_core::LogicalTime / LogicalTimeInterval. The representation (HLAinteger64Time or HLAfloat64Time, default HLAfloat64Time) is fixed per federation execution at creation.

4. Engine (microrti-engine)

4.1 Public API

pub struct Rti { /* all federation executions and all connections of this RTI */ }
pub type ConnId = u64;

impl Rti {
    pub fn new(config: RtiConfig) -> Self;
    /// A federate session appeared (before the HLA Connect service is called).
    pub fn open_connection(&mut self) -> ConnId;
    /// The same for a session whose peer the host knows: `host` becomes MOM `HLAfederateHost`.
    pub fn open_connection_from(&mut self, host: impl Into<String>) -> ConnId;
    /// Executes one federate-initiated service. Never panics on bad input: errors become ExceptionData.
    pub fn call(&mut self, conn: ConnId, request: CallRequest) -> CallResponse;
    /// Callbacks queued for this connection, in delivery order. Draining is the only way they leave.
    pub fn take_callbacks(&mut self, conn: ConnId) -> Vec<CallbackRequest>;
    /// Connections that have callbacks waiting (and clears that set).
    pub fn take_ready(&mut self) -> Vec<ConnId>;
    /// The host will tell the outcome of every callback of this connection (MOM service reports, 11.5).
    pub fn expect_callback_responses(&mut self, conn: ConnId);
    /// The federate answered the callback `take_callbacks` returned at this position (from zero).
    pub fn callback_response(&mut self, conn: ConnId, callback: u64, response: CallbackResponse);
    /// The federate name of the federate joined on this connection (chosen by the RTI if it gave none).
    pub fn federate_name(&self, conn: ConnId) -> Option<&str>;
    /// The session is gone without Disconnect: the federate is lost (4.1.6), resign it automatically.
    pub fn connection_lost(&mut self, conn: ConnId, reason: &str);
    /// Releases the connection after Disconnect / session termination.
    pub fn close_connection(&mut self, conn: ConnId);
    /// Wall-clock driven work (MOM periodic reports, update-rate throttling). Call a few times per second.
    pub fn tick(&mut self, now: std::time::Instant);
}

The engine is single threaded behind &mut self; the server wraps it in a mutex. It performs no I/O and reads no clock except the now passed to tick. What has to outlive or leave the process goes through a port the host may replace: SnapshotStore (Rti::set_snapshot_store, federation saves) and ServiceReportLog (Rti::set_service_report_log, the MOM service report logs of 11.5.2); both are in memory by default. A FOM module or MIM named by URL (12.13.3.3 a)) is not read by the engine either: the host asks Rti::fom_urls_to_read which URLs a Create or Join Federation Execution request needs (none when the service would raise an exception before it uses its modules: not connected, unauthorized, the federation execution exists, already joined, save or restore in progress, in the precedence of 4.5.5 and 4.11.5), reads them without holding the engine (microrti_fom::FomUrlReader), and hands what it read to Rti::call_with_fom_urls, which raises what could not be read as CouldNotOpen... or ErrorReading... where the module ranks among the exceptions of the service. Rti::call answers every URL as a module that cannot be opened. All state of a federation execution derives serde::Serialize + Deserialize so that federation save/restore can snapshot it.

Callback model (EVOKED / IMMEDIATE), Evoke Callback, Evoke Multiple Callbacks, Enable Callbacks and Disable Callbacks are implemented in the client library (12.13.3.2), not in the engine.

The bytes of a federation save that the engine hands to the SnapshotStore are the magic MRTISNAP, the number of the snapshot format (8, FORMAT in src/coordination/snapshot.rs), the postcard encoding of the snapshot, then the CRC-32 of all three in little-endian order. Request Federation Restore compares the magic and the format, then the checksum, before it decodes anything: a save of another format, or one damaged after it was written, is refused (4.28) with the reason in Rti::restore_error. The checksum is against accidental damage, not a signature: decoding has to stay robust on its own.

4.2 Source layout and ownership

src/lib.rs            crate docs, re-exports
src/rti.rs            Rti, RtiConfig, connection table, federation directory
src/conn.rs           Connection (connected?, credentials, joined federate, callback outbox)
src/dispatch.rs       CallRequest -> handler function -> CallResponse; common pre-checks; MOM hooks
src/meta.rs           ServiceMeta table: one row per service (name, clause, service group, flags)
src/handles.rs        handle newtypes and wire codecs
src/convert.rs        helpers between protobuf values and engine values (sets, maps, times, regions)
src/auth.rs           Authorizer trait, the predefined "HLAauthorizer" (12.5, 12.6)
src/services/federation.rs   clause 4 handlers       src/services/time.rs      clause 8 handlers
src/services/declaration.rs  clause 5 handlers       src/services/ddm.rs       clause 9 handlers
src/services/object.rs       clause 6 handlers       src/services/support.rs   clause 10 handlers
src/services/ownership.rs    clause 7 handlers
src/federation/       state of one federation execution (federates, objects, queues, regions...)
src/coordination/     synchronization points, federation save and restore, the snapshot format (4.14 to 4.35)
src/ownership/        ownership management (clause 7): the ownership state of each instance attribute
src/regions/          data distribution management (clause 9): regions, range bounds, overlap
src/timemgmt/         time management (clause 8): logical time, lookahead, queues, GALT
src/mom/              Management Object Model (clause 11)
tests/                integration tests, one file per topic, shared helpers in tests/common/

One handler function per CallRequest alternative, named after the request in snake case without the Request suffix:

pub(crate) fn publish_object_class_attributes(
    ctx: &mut Ctx<'_>,
    req: PublishObjectClassAttributesRequest,
) -> RtiResult<PublishObjectClassAttributesResponse>;

Ctx gives access to the Rti, the calling connection and (when joined) its federation execution and federate. Handlers validate arguments in the precedence order of the service’s exception list and leave no partial effect behind when they return an error.

4.3 Seams between service groups

Each service group keeps its state in its own structs (in its own files) embedded in Federation, Federate and ObjectInstance, and offers the other groups a small internal API. The seams:

  • Routing (object management): which federates receive an attribute update, an interaction, a directed interaction, a discovery, a removal. Combines publications/subscriptions (declaration management) with region overlap (DDM).
  • Region overlap (DDM): fn predicates answering “does this update / interaction / subscription pair overlap”. Without regions everything overlaps.
  • Ownership (ownership management): who owns each instance attribute; Owner::Federate(h), Owner::Rti (MOM attributes), Owner::Unowned.
  • Delivery (time management): the single place where a callback is handed to a federate: deliver(federate, callback, DeliveryClass). It decides between immediate delivery, the receive-order queue and the timestamp-order queue according to 8.1 (time-constrained state, asynchronous delivery, time advancing state) and stamps retraction handles. No other code pushes to a connection outbox. deliver stages the callback in the federation execution; dispatch commits the staged callbacks to the outboxes when the handler succeeds and drops them when it answers with an exception, and code outside a service invocation commits with Rti::commit_deliveries.
  • MOM (clause 11): behaves like a privileged internal federate that owns the MOM object instances, reacts to MOM interactions and is notified by dispatch about service invocations and exceptions.

5. FOM (microrti-fom)

Parses OMT DIF XML modules (2025 namespace; the 2010 namespace is accepted too), validates them, merges them per 1516.1-2025 4.1.4.1 and the merging rules of IEEE 1516.2-2025 (clause 7, Table 56, Annex C) for the tables the FDD keeps, and exposes the merged FDD: classes with inheritance, attributes, parameters, directed interactions, dimensions, transportation types, update rates, switches, plus the time representation and data types (needed by MOM and tooling). A repeated definition must agree with the current FDD on the columns of the FDD of 1516.1 4.1.4 (sharing of classes and directed interactions, the complete dimension table, transportation and order, reliability, rates, switches); the other columns and prose keep their first definition, and a column a definition leaves out is completed. Enumerated types and extendable variant records are united. Synchronization points, user-supplied tags, notes and the service usage table are outside the FDD (1516.1 4.1.4) and are not combined. The standard MIM is embedded in the crate. It can write the current FDD back as XML (MOM HLAcurrentFDD), with a “Composed From” reference per module.

6. Federate Protocol (microrti-fedpro)

Implements 12.13: the 24-byte header, the twelve message types, sequence numbers with wrap-around, the message history buffers, heartbeats, session resume, and the four transports (TCP 15164, TLS 15165, WebSocket, secure WebSocket). Built on tokio. It knows nothing about HLA semantics: the server side calls an RtiService trait object (implemented by microrti on top of the engine), the client side offers call(CallRequest) -> CallResponse plus a stream of CallbackRequest.

  • RTI side: Server::bind(ServerConfig) then serve(Arc<dyn RtiService>). The service is told session_opened(SessionId, CallbackSender), call, callback_response and session_closed(SessionId, CloseReason), one at a time per session, on blocking threads. A session survives its connection: it turns inactive after RTI_TIMEOUT_HEART or a broken connection, can be resumed, and is purged after RTI_TIMEOUT_PURGE (CloseReason::Lost). Callbacks pushed through a CallbackSender are sent in order; those pushed during a call of the same session follow its response. callback_response(session, callback, response) names the callback request it answers by its position among those pushed for the session, from zero; the wire carries only the sequence number.
  • Federate side: ClientSession (async) and blocking::ClientSession. A connection fault is repaired by reconnecting and resuming for up to FED_TIMEOUT_RECONNECT; pending calls wait and are neither lost nor executed twice. Responses are matched with their calls by the sequence number of the request, so the RTI may answer in any order, and blocking::ClientSession::call_timeout can give up waiting: the response that arrives afterwards is dropped, never handed to another call. Endpoint parses tcp://, tls://, ws://, wss:// and bare host[:port]; TlsMode selects encryption only or validation against trust anchors (12.13.5.1).
  • Message size: the standard sets no limit (12.13.4.5); each side has a max_message_size. A larger HLA service message is read to its end without being kept (frame::Message::Oversized), so the stream stays in step: the RTI answers an oversized call with RTIinternalError, the federate fails the call whose response is oversized; the session goes on. An oversized callback request ends the session on the federate side (it would be lost unnoticed) unless the federate is terminating the session, when no callback is delivered any more; an oversized control message is a bad message (12.13.4.7). Over WebSocket this holds up to 1 MiB above the limit: the WebSocket layer refuses a larger message before reading it, the stream cannot be followed past it, and the receiving side ends the session as for a bad message (the RTI deletes it, so the federate cannot resume it).

7. Client (microrti-client)

RtiAmbassador offers every service of clauses 4 to 10 as a typed, blocking Rust method; FederateAmbassador is a trait with one method per callback and empty defaults. Both callback models are supported (EVOKED with evoke_callback / evoke_multiple_callbacks, IMMEDIATE on a dedicated thread). The ambassador talks to an RtiLink, opened at Connect by a LinkFactory selected by the scheme of the RTI address (Connectors). The links:

Cargo featureModuleLink
fedpro (default)fedproFedProLink: one Federate Protocol session to any HLA 4 RTI
embeddedembeddedEmbeddedRti: an engine in the federate’s process, with a tick thread
test-utiltestingMockLink: scripted, for tests

With fedpro, RtiAmbassador::new() reaches an RTI for the addresses tcp://host[:port], tls://, ws://host[:port][/path], wss:// and bare host[:port] (TCP, port 15164); an empty address is tcp://localhost:15164. The settings of the federate (Table 32 and TLS) are the fields of fedpro::FedProOptions, set in code on a FedProConnector or as KEY=VALUE lines in the additional settings of the RtiConfiguration: FED_INT_HEART, FED_TIMEOUT_HEART, FED_TIMEOUT_RECONNECT, FED_INT_RECONNECT, FED_TIMEOUT_CONNECT (seconds), TLS_TRUST_ANCHORS (PEM file), TLS_SERVER_NAME. The other lines are for the RTI, which receives the settings unchanged (microrti_core::settings).

Seen from the federate, the link is part of the RTI. The ConfigurationResult of Connect (4.2) is the answer of the RTI completed by the ambassador with RtiLink::configuration_usage: the RTI address the link reached (or the scheme that chose its connector), the keys it applied, those it could not parse. A setting that cannot be parsed does not stop the connection (4.2): SettingsFailedToParse. One deliberate deviation from 4.2: on tls:// and wss://, without trust anchors set in code, a TLS_* line that cannot be used (an unknown key such as TLS_TRUST_ANCHOR, an empty value, a line without =) fails Connect with ConnectionFailed naming the line: it may be the trust anchors written wrong, and connecting would silently drop the validation of the RTI certificate (12.13.5.1). The engine answers for itself only: no named configurations, the address unused, the keys other than FED_* and TLS_* named as ignored.

Faults: an RTI that cannot be reached at Connect is ConnectionFailed; a resumed session is invisible; a session lost for good gives NotConnected and the Connection Lost callback (4.4). Disconnect terminates the session and closes the transport.

Extensions of the library, each said to be one in its documentation: RtiAmbassador::close ends the connection without Disconnect (the RTI resigns a federate still joined as a lost one, 4.1.6), also from inside a callback; RtiAmbassador::with_call_timeout gives a handle whose services wait at most a given time for the RTI (RtiLink::call_timeout; the RTI may still carry out a service given up); evoke_callback_counted and evoke_multiple_callbacks_counted tell how many callbacks they delivered. EmbeddedRti is built on local::LocalRtiHub and is itself a connector (EmbeddedRti::ambassador(), EmbeddedRti::register(scheme)).

With embedded, the federates of one process share one RTI without a network. Each RtiAmbassador has a link of its own to the same engine, a service invocation is a function call under the lock of the hub, and a thread calls Rti::tick through the hub every 100 ms (DEFAULT_TICK_PERIOD). The federates share federation executions as they would through a server. The FOM modules named by URL are read as the server reads them, by a FomUrlReader (EmbeddedRti::set_fom_url_policy, set_fom_url_reader; by default every file:, http: and https: URL), by the threads of the reader with the same limits, while the calling federate waits without the lock of the hub (LocalRti::prepare_call).

flowchart TB
  subgraph process["One process"]
    direction LR
    fedA["<b>Federate A</b><br/>RtiAmbassador"]
    fedB["<b>Federate B</b><br/>RtiAmbassador"]
    tick["<b>Tick thread</b><br/>Rti::tick every 100 ms"]
    subgraph embedded["EmbeddedRti: microrti-client, feature embedded"]
      hub["<b>LocalRtiHub</b><br/>one lock around the engine,<br/>a link and a callback queue per federate"]
      engine["<b>microrti-engine</b><br/>Rti::call, Rti::take_callbacks"]
      hub --> engine
    end
    fedA -->|"function call"| hub
    fedB -->|"function call"| hub
    tick --> hub
  end
  classDef core stroke-width:2.5px
  class engine core

8. Server (microrti)

A library and the binary microrti. RtiServer::start(ServerSettings) creates one engine, binds the listeners and serves on its own threads; RunningServer gives local_addrs(), local_endpoint(kind), status() (sessions, connected federates, joined federates, federation executions, counters) and shutdown().

  • RID (settings): a TOML file (Rid) with command line options laid over it, resolved into ServerSettings. Keys: [[listener]] (transport = tcp / tls / ws / wss, address), tls_certificate_chain, tls_private_key, tls_self_signed, rti_timeout_heart, rti_timeout_purge (Table 31, seconds), max_message_size, tick_period_ms, service_report_directory (one MOM service report log file per federate, 11.5.2), save_directory (federation saves as files, 4.1.2: FileSnapshotStore, given to the engine by RtiServer::start; without it they stay in memory), fom_urls (all, the default: every file:, http: and https: URL; none), fom_url_directory (only the regular files of this directory, named by file: URLs, relative ones relative to it, .., symbolic links that lead out and what is not a regular file the RTI can open refused alike, http: and https: refused; FomUrlPolicy::directory; an empty value is an error; it excludes fom_urls), fom_url_timeout (seconds, default 30: connection and download of one module), fom_url_root_certificates (PEM: the roots https: servers are verified against instead of the trust store of the system); together ServerSettings::fom_url_reader, used by RtiServer::start and RtiServer::start_with_rti, logged once at start, shown by check-config), log_level, [authorization] (enabled, authorizer, password or password_env or password_file). Every other key the engine’s RtiConfig serializes is accepted and handed to the engine; an unknown key is an error. Defaults: TCP on 0.0.0.0:15164, plus TLS on 0.0.0.0:15165 when a certificate is configured. Every key is documented in crates/microrti/microrti.example.toml.
  • Sessions and the engine (service): a session is one engine connection, opened with the address of its peer (CallbackSender::peer_addr, MOM HLAfederateHost). Each call locks the engine, runs the service and takes the ready callbacks under the lock (outbox::stage); they are handed to the CallbackSenders after the lock is released, one flusher at a time, which keeps the order of each connection. The same happens after every tick (default 100 ms, own thread) and every session end. A Create or Join Federation Execution that names modules by URL is the exception to “one lock per call”: under the lock Rti::fom_urls_to_read; when it names nothing, the call follows under the same lock; otherwise the lock is released and the FomUrlReader reads them on threads of its own (at most 8 calls hold a reader at once, from the start of the reading to the end of the execution, the contents read holding it; the others wait in turn, without a thread; per call the first 64 distinct URLs, 8 MiB per module, 16 MiB in all and one time limit), while the service gives its pool thread back (RtiService::begin_call answers CallOutcome::Pending, which the session awaits). The engine lock is taken again for Rti::call_with_fom_urls. A federate that terminates its session has the call abandoned (PendingResponse): not executed and answered so when its execution has not begun (the flag is read under the engine lock), executed and truly answered otherwise; a session that ends otherwise drops it. session_closed(Terminated) is close_connection; session_closed(Lost) is connection_lost then close_connection. Disconnect keeps the session. A callback response goes to the engine (Rti::callback_response) only while the engine waits for the outcome of a callback (MOM service reports, 11.5); the others take no lock.
  • Bookkeeping and log: connected / joined / federation executions are derived from the Connect, Disconnect, Create, Destroy, Join and Resign requests that succeed and from the Federate Resigned and Connection Lost callbacks. The engine is asked two things only: after a join, the federate name (Rti::federate_name), which the RTI chooses when the federate gives none (4.11); after Request Federation Restore, why the restore failed (Rti::restore_error), which no callback carries (4.28, 4.32). Logged with tracing at info; a federate is named by its federate name and its federate type. A restore that failed is a warning with its reason, for example a save file whose checksum does not match (damaged) or that cannot be decoded. A service refused by the authorization service (Unauthorized, InvalidCredentials, 4.1.7) is a warning with the address of the peer; the other exceptions are logged at debug. microrti-fedpro logs a failed TLS handshake at info with the address of the peer, except when the peer closed or reset the connection during it (port scans), which stays at debug, and except the same failure from the same address again within a minute (the repeated connection attempts of a client at session start-up), which is a debug line with repeated=true.
  • Binary: microrti [--config FILE] [--listen [TRANSPORT://]IP[:PORT]]... [options], microrti check-config [FILE] (validates, prints the effective settings in RID syntax, exit status 2 on an unusable RID, a save directory that cannot be created or written included, which it finds without creating it), microrti --version. One listening on <address> line per listener on the standard output, the log on the standard error. A thread of its own writes the log and holds at most 4096 lines: when nobody reads the standard error, lines are dropped rather than the federates kept waiting, and their number is logged at shutdown; that line is lost as well when the standard error is still blocked then, since the process does not wait for it. The records of crates that log with log join the log, those of rustls one level lower (debug, its own debug records at trace): the failed handshakes are logged by microrti-fedpro, and some of its warnings are harmless, such as the user_canceled alert some clients send before closing. SIGINT / SIGTERM shut down in an orderly way.
  • End-to-end tests: crates/microrti/tests/, helpers in tests/common/mod.rs (TestRti, Connect, Federate, TcpProxy, basic_scenario).

9. Quality gates

cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-features --no-fail-fast

Every service has tests for its normal behaviour and for each exception it can raise. End-to-end tests run real federates against a real server over each transport.

Two GitHub workflows run these checks. CI (.github/workflows/ci.yml) runs the three gates and a compile check with the minimum supported Rust version on every push to main and every pull request. Interoperability (.github/workflows/interop.yml) runs every week and by hand, never on a pull request, because it downloads third-party code: it builds the server once, then drives it with the two third-party clients of interop/, the Java one (interop/pitch-fedpro) in single and pair mode over TCP, WebSocket, TLS and secure WebSocket, the C++ one (interop/pitch-fedpro-cpp) in both modes over TCP, its only transport. Each run uses every option group of its harness and stops at the first failed step; a failed step fails the job and is named in an annotation, and the output of the harness and the server log are kept as an artifact of the run. interop/ci.sh <java|cpp> <transport> <single|pair> makes one of these runs on a workstation, the same way. Actions are pinned by commit SHA in every workflow.

Hostile input

No input that comes from the network or from a federate may make MicroRTI panic or wait without end. The three ways in are attacked with inputs generated in mass, by campaigns that are part of the normal suite (a few seconds in all) and need nothing but stable Rust: a seeded generator (splitmix64) and mutations written in the tests, in tests/fuzz/mod.rs of each crate concerned.

Way inCampaigns
Federate Protocol (12.13.4, 12.13.5)microrti-fedpro/tests/hostile.rs: byte streams decoded whole and in pieces (same result, decoder failed for good after a bad message, no reservation on the word of a header), protobuf payloads, TLS material on ServerTls::check, addresses, a federate against a hostile RTI, an RTI against hostile WebSocket peers; microrti/tests/hostile_wire.rs: a real server against hostile TCP peers (noise, sessions with wrong numbers, types, identifiers, payloads, oversized messages, resumes), then damaged save files under a live federation (most with their checksum computed again)
Service requestsmicrorti-engine/tests/hostile_calls.rs: requests generated from the protobuf schema of Annex D (protox), handles learned from the responses, against a populated federation; damaged saves restored and used, most with their checksum computed again so that decoding goes deep, the others refused
FOM modulesmicrorti-fom/tests/hostile.rs: mutations of the modules of fom/ and of the examples (elements removed, repeated, moved, nested thousands deep, hostile values, cycles of types, DTDs and entities), documents of the OMT grammar, large tables in linear time
Encoded valuesmicrorti-encoding/tests/hostile_fom.rs: every data type of the MIM and of the modules, codecs of damaged data type tables; microrti-encoding/tests/allocation.rs: what decoding allocates, counted with stats_alloc, stays within 64 KiB plus 128 octets per octet of input whatever the counts announce

A panic of any thread (tokio tasks and the blocking threads of the server included) is counted by a panic hook in the network campaigns. Three variables steer every campaign:

MICRORTI_FUZZ_ITERATIONS=<n>   # cases per campaign instead of the default, for a long campaign
MICRORTI_FUZZ_SEED=<n>         # another seed (the default seed is fixed per campaign)
MICRORTI_FUZZ_CASE=<n>         # plays one case alone

A case that fails prints its seed and number, replay it alone with MICRORTI_FUZZ_SEED=... MICRORTI_FUZZ_CASE=..., and plays the same input again. A case of a network campaign is played against a server that the cases before it have not touched, and threads are scheduled by the system: the same input may then behave differently. A long campaign, one crate at a time:

MICRORTI_FUZZ_ITERATIONS=3000 MICRORTI_FUZZ_SEED=1 cargo test -p microrti-engine --test hostile_calls -- --nocapture
MICRORTI_FUZZ_ITERATIONS=2000000 cargo test -p microrti-encoding --all-features --test allocation -- --nocapture

10. Reproducibility

The engine is a deterministic state machine (section 4): the same sequence of service calls gives the same callbacks. Between federates on separate connections the order in which the calls reach the RTI is not fixed, so what follows is about a federation, and it is what crates/microrti/tests/reproducibility.rs checks by experiment, not more: five federates on their own TCP sessions, whose behaviour depends on everything they receive, played many times with a different join order and random pauses.

What a federate receives in timestamp order (timestamps, classes, values, producing federates by name) and the logical times it is granted are the same in every execution when the federation keeps to this:

  • every federate is time-regulating and time-constrained before the first timestamped message is sent, and stays so (clause 8); in the test a start signal plays the part of a synchronization point (4.14). A federate that becomes time-regulating later is admitted where it cannot send below what the time-constrained federates have received (8.2), which can be a timestamp whose messages they have received already: its own messages with that timestamp then come after them;
  • everything a result depends on is sent in timestamp order, and the federates advance with Time Advance Request (8.8);
  • a federate acts on the timestamp-order messages and on its grants only: not on receive-order messages, not on the moment an instance is discovered, not on handle values, not on the wall clock;
  • no two federates send with the same timestamp, or each federate sorts the messages of one timestamp by a key of its own (their content, for example) before it acts on them at the grant.

The last condition comes from the standard: timestamp order says nothing about messages with equal timestamps (clause 3, “timestamp order”; 8.1.4). MicroRTI delivers them in the order in which they reached it, a Remove Object Instance behind the others of its timestamp. From one federate that is the order of its calls, hence reproducible; between federates it is the order of arrival, and in the test it differed in every execution. Federates that neither avoid shared timestamps nor sort diverged in every execution of the experiment.

Not reproducible, by nature: the order of receive-order messages, the handles of federates and object instances (given in order of arrival), whatever the wall clock drives (MOM periodic reports, update rate reduction, timeouts). This includes the Remove Object Instance callbacks of a federate that resigns or is lost (4.12): they are receive-order messages and take effect when they are sent, so a federate drops the updates of those instances that are still in its queue and not due yet (6.11.3 c), because it has not asked to advance that far or because another time-regulating federate holds its GALT below them. Which updates it receives then depends on the order in which the resignation and the calls of the other federates reach the RTI; the condition “stays so” above excludes it. Not covered by the test: Time Advance Request Available, Next Message Request Available and Flush Queue Request, which by definition deliver messages of a timestamp at which more can follow (8.9, 8.11, 8.12); messages with the final logical time, which GALT never passes (8.1.1); zero lookahead; save and restore; ownership transfer; DDM.

The price is latency. A federate waiting for the grant of a Time Advance Request receives a message stamped with its GALT only when no more can follow at that timestamp, that is when GALT passes it: when the federates that could still send with that timestamp ask to advance beyond it or stop being time-regulating, and at the latest before the grant (8.8). A message stamped with the logical time of its sender plus its lookahead thus arrives at least one request of the sender later than it could. No grant comes later for it, since the condition of a grant does not depend on what was delivered, and federates that wait for the answer of each other through their requests keep advancing (two_federates_that_wait_for_the_answer_of_each_other_keep_advancing in timemgmt/tests/held.rs, with each of the four advance services). A federate that stays in the Time Granted state until a receiver of such a message reacts, by a receive-order message with asynchronous delivery (8.15) or outside the RTI, waits forever: it asks to advance first. The standard promises such a message before the grant, not earlier.

cargo test -p microrti --test reproducibility                       # 4 executions per variant
MICRORTI_REPRO_RUNS=200 cargo test -p microrti --test reproducibility -- --nocapture
MICRORTI_REPRO_RUNS=200 cargo test -p microrti --test reproducibility -- --ignored --nocapture

The last line runs the federates that do not sort; it reports how many executions differ and asserts nothing. MICRORTI_REPRO_DUMP=<directory> writes the journals of the compared executions. A failure names the seed of the pauses: MICRORTI_REPRO_SEED=<seed> with the number of executions it gives plays the same join orders and pauses again (the threads are still scheduled by the system).

This page is docs/ARCHITECTURE.md of microrti/microrti, at v0.5.1.