Agentra LabsAgentra Labs DocsPublic Documentation

Get Started

Data Structures

This document specifies every data structure used in AgenticComm's core library and persistence layer. All structures are defined in Rust and serialized using bincode for on-dis...

This document specifies every data structure used in AgenticComm's core library and persistence layer. All structures are defined in Rust and serialized using bincode for on-disk storage. Field-level constraints, defaults, and invariants are documented for each structure.

Message

The fundamental unit of communication. Every message is immutable after creation -- once persisted, its fields cannot be modified.

Fields

FieldTypeRequiredDefaultDescription
idu64autoauto-incrementUnique message identifier within the store. Assigned by the engine at send time.
message_typeMessageTypeyes--One of: Text, Command, Query, Response, Broadcast, Notification, Acknowledgment, Error.
senderStringyes--Participant ID of the sender. Max 128 characters.
channel_idu64yes--ID of the channel this message belongs to.
contentStringyes--Message body. Max 1 MB (1,048,576 bytes) as UTF-8.
topicOption<String>noNoneTopic string for pub/sub routing. Dot-separated hierarchy. Max 256 characters.
correlation_idOption<String>noNoneUUID linking related messages (query-response pairs, command-acknowledgment chains).
priorityPrioritynoNormalDelivery priority: Critical(0), High(1), Normal(2), Low(3), Background(4).
metadataOption<MessageMetadata>noNoneStructured key-value metadata attached to the message.
created_atu64autoUnix timestampCreation time in seconds since Unix epoch (UTC).
delivered_atOption<u64>autoNoneTime the message was delivered. Set by the engine.
acknowledged_atOption<u64>autoNoneTime the message was acknowledged. Set when an ack is received.
ttlOption<u64>noNoneTime-to-live in seconds. Messages past TTL are not delivered.
statusMessageStatusautoCreatedCurrent lifecycle status: Created, Sent, Delivered, Acknowledged, Failed, DeadLetter, Archived.
retry_countu32auto0Number of delivery attempts. Incremented on each retry.
signatureOption<Vec<u8>>noNoneCryptographic signature from AgenticIdentity. Ed25519 signature bytes.

MessageType Enum

#[repr(u8)]
pub enum MessageType {
    Text = 0,
    Command = 1,
    Query = 2,
    Response = 3,
    Broadcast = 4,
    Notification = 5,
    Acknowledgment = 6,
    Error = 7,
}

Serialized as a single u8. Values 8-255 are reserved for future message types and must be rejected by parsers.

MessageStatus Enum

#[repr(u8)]
pub enum MessageStatus {
    Created = 0,
    Sent = 1,
    Delivered = 2,
    Acknowledged = 3,
    Failed = 4,
    DeadLetter = 5,
    Archived = 6,
}

Priority Enum

#[repr(u8)]
pub enum Priority {
    Critical = 0,
    High = 1,
    Normal = 2,
    Low = 3,
    Background = 4,
}

Validation Rules for Message

  • sender must be non-empty and at most 128 bytes. Must match pattern [a-zA-Z0-9_-]+.
  • content must be non-empty. Maximum 1,048,576 bytes.
  • topic, if present, must be non-empty, at most 256 bytes, and match pattern [a-zA-Z0-9_-]+(\.[a-zA-Z0-9_*#-]+)*.
  • correlation_id, if present, must be a valid UUID v4 string.
  • ttl, if present, must be > 0.
  • channel_id must refer to an existing channel in the store.

Channel

A named communication context. Channels own messages and define delivery semantics.

Fields

FieldTypeRequiredDefaultDescription
idu64autoauto-incrementUnique channel identifier.
nameStringyes--Human-readable channel name. Max 128 characters.
channel_typeChannelTypeyes--One of: Direct, Group, Broadcast, PubSub.
ownerStringyes--Participant ID of the channel creator/owner.
participantsVec<Participant>auto[owner]List of participants with roles.
configChannelConfignoChannelConfig::default()Channel configuration (delivery semantics, retention, etc.).
stateChannelStateautoActiveCurrent lifecycle state: Active, Paused, Draining, Closed.
created_atu64autoUnix timestampCreation time in seconds since Unix epoch.
modified_atu64autoUnix timestampLast modification time. Updated on config changes, participant changes.
message_countu64auto0Total number of messages in this channel.
descriptionOption<String>noNoneOptional human-readable description. Max 1024 characters.
tagsVec<String>no[]Optional tags for categorization. Each tag max 64 characters.

ChannelType Enum

#[repr(u8)]
pub enum ChannelType {
    Direct = 0,
    Group = 1,
    Broadcast = 2,
    PubSub = 3,
}

ChannelState Enum

#[repr(u8)]
pub enum ChannelState {
    Active = 0,
    Paused = 1,
    Draining = 2,
    Closed = 3,
}

Validation Rules for Channel

  • name must be non-empty, at most 128 bytes. Must match pattern [a-zA-Z0-9_-]+(/[a-zA-Z0-9_-]+)*. Slashes are allowed for hierarchical naming (e.g., team/backend/alerts).
  • owner must be a valid participant ID.
  • Direct channels must have exactly 2 participants.
  • Broadcast channels must have exactly 1 participant with Owner role.
  • Channel names must be unique within a store.
  • Maximum 100 tags per channel, each tag at most 64 bytes.

Participant

A member of a channel with an assigned role.

Fields

FieldTypeRequiredDefaultDescription
idStringyes--Participant identifier. Max 128 characters.
roleParticipantRolenoMemberRole within the channel.
joined_atu64autoUnix timestampWhen the participant joined.
identity_idOption<String>noNoneAgenticIdentity aid_... identifier for verified participants.

ParticipantRole Enum

#[repr(u8)]
pub enum ParticipantRole {
    Owner = 0,
    Member = 1,
    Observer = 2,
}

Subscription

A pub/sub subscription linking a participant to a topic pattern on a channel.

Fields

FieldTypeRequiredDefaultDescription
idu64autoauto-incrementUnique subscription identifier.
channel_idu64yes--PubSub channel this subscription belongs to.
subscriberStringyes--Participant ID of the subscriber.
topic_patternStringyes--Topic pattern to match. Supports exact, wildcard (*), and multi-level wildcard (#).
match_modeMatchModeautoinferredInferred from pattern: Exact, Wildcard, MultiLevel.
created_atu64autoUnix timestampWhen the subscription was created.
activeboolautotrueWhether the subscription is active.
filterOption<MessageFilter>noNoneOptional additional filter applied to matched messages.

MatchMode Enum

#[repr(u8)]
pub enum MatchMode {
    Exact = 0,    // "build.frontend.complete"
    Wildcard = 1, // "build.*.complete" (single segment wildcard)
    MultiLevel = 2, // "build.#" (zero or more segments)
}

Match mode is inferred from the topic pattern at subscription creation time. Patterns containing * are Wildcard. Patterns ending with # are MultiLevel. All other patterns are Exact.

ChannelConfig

Configuration controlling channel behavior.

Fields

FieldTypeRequiredDefaultDescription
deliveryDeliveryModenoAtMostOnceDelivery guarantee: AtMostOnce, AtLeastOnce, ExactlyOnce.
max_message_sizeu64no1048576 (1 MB)Maximum message content size in bytes.
max_participantsOption<u32>noNone (unlimited)Maximum number of participants.
retentionRetentionPolicynoForeverMessage retention policy.
ack_timeoutOption<u64>noNoneSeconds to wait for acknowledgment before retry/escalation.
max_retriesu32no3Maximum delivery retry attempts before dead-lettering.
retry_backoff_msu64no1000Initial retry backoff in milliseconds. Doubles on each retry.
echoboolnofalseWhether senders receive their own messages.
sticky_messagesboolnofalseWhether new participants receive messages sent before they joined.
priority_orderingboolnotrueWhether to respect message priority for delivery ordering.

DeliveryMode Enum

#[repr(u8)]
pub enum DeliveryMode {
    AtMostOnce = 0,  // Fire and forget. No retry.
    AtLeastOnce = 1, // Retry until acknowledged or max_retries exhausted.
    ExactlyOnce = 2, // Deduplication + at-least-once. Requires correlation_id.
}

RetentionPolicy Enum

pub enum RetentionPolicy {
    Forever,
    Duration(u64),  // seconds
    Count(u64),     // max messages
    Size(u64),      // max bytes
}

Serialized as: tag byte (0=Forever, 1=Duration, 2=Count, 3=Size) followed by a u64 value for non-Forever variants.

MessageFilter

A filter used to query messages by various criteria.

Fields

FieldTypeRequiredDefaultDescription
channel_idsOption<Vec<u64>>noNoneFilter to messages in these channels.
senderOption<String>noNoneFilter to messages from this sender.
message_typesOption<Vec<MessageType>>noNoneFilter to these message types.
topic_patternOption<String>noNoneFilter by topic (supports wildcards).
afterOption<u64>noNoneMessages created after this timestamp.
beforeOption<u64>noNoneMessages created before this timestamp.
statusOption<Vec<MessageStatus>>noNoneFilter by message status.
priorityOption<Vec<Priority>>noNoneFilter by priority level.
correlation_idOption<String>noNoneFilter by correlation ID (thread).
content_patternOption<String>noNoneRegex pattern to match against message content.
limitu64no100Maximum number of results to return.
offsetu64no0Skip this many results (pagination).
sort_bySortFieldnoCreatedAtField to sort results by.
sort_orderSortOrdernoDescendingSort direction.
include_archivedboolnofalseInclude archived messages in results.

SortField Enum

pub enum SortField {
    CreatedAt,
    Priority,
    Sender,
    MessageType,
}

SortOrder Enum

pub enum SortOrder {
    Ascending,
    Descending,
}

MessageMetadata

Structured key-value metadata attached to a message. Used for application-specific data that does not fit into the core message fields.

Fields

FieldTypeRequiredDefaultDescription
entriesBTreeMap<String, MetadataValue>noemptyKey-value pairs. Keys are strings, max 128 characters. Max 64 entries.

MetadataValue Enum

pub enum MetadataValue {
    String(String),   // Max 4096 bytes
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Null,
}

Metadata is serialized as a length-prefixed sequence of key-value pairs. Keys are sorted (BTreeMap) for deterministic serialization.

CommStore

The in-memory representation of a .acomm file. Holds all channels, messages, subscriptions, and indexes.

Fields

FieldTypeDescription
pathPathBufFile path of the .acomm file.
channelsHashMap<u64, Channel>All channels, keyed by channel ID.
messagesVec<Message>All messages, ordered by creation time.
subscriptionsHashMap<u64, Subscription>All subscriptions, keyed by subscription ID.
dead_lettersVec<Message>Messages that failed delivery and exhausted retries.
next_channel_idu64Next available channel ID.
next_message_idu64Next available message ID.
next_subscription_idu64Next available subscription ID.
modifiedboolDirty flag. Set to true when any mutation occurs.
created_atu64Store creation timestamp.
modified_atu64Last modification timestamp.

Invariants

  • next_channel_id is always greater than the maximum channel ID in channels.
  • next_message_id is always greater than the maximum message ID in messages.
  • Every message's channel_id references a channel in channels.
  • Every subscription's channel_id references a PubSub channel in channels.
  • Direct channels have exactly 2 participants.
  • Broadcast channels have exactly 1 owner; other participants are observers.

Index Structures

Indexes are maintained in-memory for fast lookup and serialized to the .acomm file for persistence.

ChannelMessageIndex

Maps channel IDs to the message IDs belonging to that channel.

pub struct ChannelMessageIndex {
    // channel_id -> sorted Vec of message_ids
    index: HashMap<u64, Vec<u64>>,
}

TimestampIndex

Maps time ranges to message IDs for fast temporal queries.

pub struct TimestampIndex {
    // Sorted vec of (timestamp, message_id) for binary search
    entries: Vec<(u64, u64)>,
}

Temporal queries use binary search on the entries vector. A query for messages between timestamp A and B performs two binary searches (lower bound on A, upper bound on B) and returns the slice between them.

TopicIndex

Maps topic strings to message IDs for fast pub/sub queries.

pub struct TopicIndex {
    // exact topic -> sorted Vec of message_ids
    exact: HashMap<String, Vec<u64>>,
    // topic segment count for wildcard matching
    segment_cache: HashMap<String, Vec<String>>,
}

SenderIndex

Maps sender participant IDs to their message IDs.

pub struct SenderIndex {
    // sender -> sorted Vec of message_ids
    index: HashMap<String, Vec<u64>>,
}

CorrelationIndex

Maps correlation IDs to all messages in the thread.

pub struct CorrelationIndex {
    // correlation_id -> sorted Vec of message_ids
    index: HashMap<String, Vec<u64>>,
}

Serialization

Bincode

All structures are serialized to binary format using bincode (version 2). Bincode is chosen over JSON for three reasons:

  1. Compact: Bincode produces 5-10x smaller output than JSON for the same data.
  2. Fast: Serialization and deserialization are zero-allocation for fixed-size types.
  3. Type-safe: Bincode preserves Rust type information, preventing deserialization of incompatible data.

Compression

Message content is compressed using flate2 (gzip level 6). The compression is applied to the content block as a whole, not per-message, because adjacent messages often share vocabulary (agent names, technical terms) that compress better together.

Compression ratio benchmarks:

Content TypeRatioNotes
Agent conversations3.2:1Repetitive vocabulary, structured text
Code snippets2.8:1Syntax keywords, indentation
JSON payloads4.1:1Repeated keys, structured data
Binary attachments1.1:1Already compressed data gains little

Endianness

All multi-byte integers are stored in little-endian format, matching bincode's default behavior and the native byte order of x86-64 and ARM64 platforms.