Skip to content

unaiverse.networking.p2p.messages

Two kinds of traffic travel between nodes. The Session messages (handshake, keep-alive, reconnection, close) are SessMsg objects on their own protocols. Everything else (profiles, stream samples, interactions, behaviors, statistics) is a chat message. This module defines the class Msg that represents it.

A Msg is a plain value object. Its fields are Python values (strings and a content that is a dict, a list or a dict of samples) and the class owns its wire codec in to_bytes and from_bytes. The codec writes the binary message format of the SDK. The codec imports its dependencies (the generated message classes, torch, PIL, gzip) only inside those two methods. Importing this module therefore loads nothing beyond the standard library. The same module also works in the browser runtime because there the codec runs on the JavaScript side.

The path of a chat message through the node is the following.

  1. The sender builds a Msg in NodeConn with its own peer ID as sender, a channel and its token in piggyback.
  2. P2P.send or P2P.broadcast encodes it with to_bytes in a worker thread and hands the bytes to the native networking library.
  3. On the receiver, P2P.get_messages decodes it with from_bytes and drops it when sender differs from the peer ID that the transport verified.
  4. NodeConn.get_messages checks the token in piggyback and replaces it with the node ID of the sender. The node then dispatches the message on its content_type.

The developer meets Msg objects when reading the internals of the node or when writing tests. To talk to another agent, an agent calls the methods of Agent and the SDK builds the messages. It never builds a Msg itself.

Msg

Msg(sender: str | None = None, content: Any = None, timestamp_net: str | None = None, channel: str | None = None, content_type: str = MISC, piggyback: str | None = None)
Source code in unaiverse/networking/p2p/messages.py
def __init__(self,
             sender: str | None = None,
             content: Any = None,
             timestamp_net: str | None = None,
             channel: str | None = None,
             content_type: str = MISC,
             piggyback: str | None = None) -> None:
    """Creates a new message from native Python fields.

    The content is kept as-is (a dict for json types, a dict of samples for stream_sample, a list for
    stats_update); it is encoded to protobuf only in to_bytes. Use from_bytes to rebuild a Msg off the wire.

    Args:
        sender: The peer id of the sender (required).
        content: The content of the message (default: None, meaning no content).
        timestamp_net: The network timestamp (default: None, meaning now, in UTC).
        channel: The channel of the message (default: None, meaning "<unknown>").
        content_type: One of the content types of this class (default: MISC).
        piggyback: The piggyback string (default: None, meaning empty).
    """

    # Sanity checks
    assert sender is not None, "Sender must be specified for a new message."
    assert isinstance(sender, str), "Sender must be a string"
    assert timestamp_net is None or isinstance(timestamp_net, str), "Invalid timestamp_net"
    assert channel is None or isinstance(channel, str), "Invalid channel"
    assert content_type in Msg.CONTENT_TYPES, "Invalid content type"

    self._sender = sender
    self._timestamp_net = timestamp_net if timestamp_net is not None else \
        datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S.%f")
    self._content_type = content_type if content_type is not None else self.MISC
    self._channel = channel if channel is not None else "<unknown>"
    self._piggyback = piggyback if piggyback is not None else ""

    # None or the sentinel mean "no content" (unset oneof on the wire).
    self._content = self._EMPTY if (content is None or content == self._EMPTY) else content

A message of the chat path with its own codec.

Argument Type Default Meaning
sender str None The peer ID of the sender on the network the message travels on. It is required and None fails an assert.
content Any None The content as a Python value (see the table of content types). None means no content.
timestamp_net str \| None None The time of creation. None takes the current UTC time in the format "%Y-%m-%d %H:%M:%S.%f".
channel str \| None None The channel of the message. None becomes "<unknown>".
content_type str Msg.MISC One of the content types of the class. Any other value fails an assert.
piggyback str \| None None The string carried next to the content. None becomes "".

The checks are assert statements. Python run with -O skips them and a wrong value then travels to the codec.

The channel names the conversation. A direct message uses <sender peer ID>::dm:<receiver peer ID>-<content type> with an optional ~<trail> and a broadcast uses <owner peer ID>::ps:<topic>. The native networking library routes on this string. P2P.send_message_to_peer rejects a direct channel without ::dm: and P2P.broadcast_message rejects a broadcast channel without ::ps:.

The piggyback string is the node token of the sender followed by one character ("0" or "1") that tells whether the sender is an inspector. Once the receiver has checked the token, the string holds the node ID of the sender followed by the same character.

P2P.get_messages also gives every received message an attribute wire_size that holds the length of its encoded bytes. The node uses it to bound the memory of the messages that wait for the end of a tick.

from unaiverse.networking.p2p.messages import Msg

msg = Msg(sender="12D3KooWSender",
          content={"addresses": ["/ip4/203.0.113.7/tcp/4001/p2p/12D3KooWSender"]},
          channel="12D3KooWSender::dm:12D3KooWWorld-address_update",
          content_type=Msg.ADDRESS_UPDATE,
          piggyback="<token>0")
wire = msg.to_bytes()
same = Msg.from_bytes(wire)
assert same.content == msg.content

PROFILE class-attribute instance-attribute

PROFILE = 'profile'

"profile". The message that carried the profile of a node in the old handshake. The Session handshake now carries profiles and the node ignores a received PROFILE with a log line.

ADDRESS_UPDATE class-attribute instance-attribute

ADDRESS_UPDATE = 'address_update'

"address_update". The new addresses of an agent, sent to its world node as {"addresses": [...]}. The world node stores them for the roster it publishes.

STREAM_SAMPLE class-attribute instance-attribute

STREAM_SAMPLE = 'stream_sample'

"stream_sample". Samples of one or more data streams. The content is a dict stream name -> {"data": ..., "data_tag": int, "data_uuid": str | None} and data is a torch.Tensor, a PIL.Image.Image, a str or a FileContainer. This is the only content type with a dedicated encoding (see to_bytes) and the only one that can travel as a file message.

ROLE_SUGGESTION class-attribute instance-attribute

ROLE_SUGGESTION = 'role_suggestion'

"role_suggestion". A new role that the world node gives to an agent. The agent accepts it only from its world node and only when the content names its own world peer ID.

INTERACTION class-attribute instance-attribute

INTERACTION = 'interaction'

"interaction". An interaction request from one agent to another (see Interactions).

INTERACTION_STATUS class-attribute instance-attribute

INTERACTION_STATUS = 'interaction_status'

"interaction_status". The status of an interaction (accepted, rejected, completed and the others) sent back to the agent that asked for it.

HSM class-attribute instance-attribute

HSM = 'hsm'

"hsm". A request to change the behavior (the hybrid state machine) of an agent. An agent accepts it only from a world master of its world.

MISC class-attribute instance-attribute

MISC = 'misc'

"misc". A message with no predefined meaning and the default content type of the constructor. The node logs it and takes no action.

GET_CV_FROM_ROOT class-attribute instance-attribute

GET_CV_FROM_ROOT = 'get_cv_from_root'

"get_cv_from_root". A notice that the CV of the receiver changed on the UNaIVERSE server. The receiver downloads its CV again and then a new token that carries the new CV hash.

BADGE_SUGGESTIONS class-attribute instance-attribute

BADGE_SUGGESTIONS = 'badge_suggestions'

"badge_suggestions". A list of badges that an agent suggests for other agents and sends to the world node. Only a world node acts on it.

INSPECT_ON class-attribute instance-attribute

INSPECT_ON = 'inspect_on'

"inspect_on". Turns on the inspector mode of a node. The node accepts it only from the inspector node it expects.

INSPECT_CMD class-attribute instance-attribute

INSPECT_CMD = 'inspect_cmd'

"inspect_cmd". A command of the inspector in the form {"cmd": ..., "arg": ...}. The node runs it only after an INSPECT_ON of the same inspector.

WORLD_AGENTS_LIST class-attribute instance-attribute

WORLD_AGENTS_LIST = 'world_agents_list'

"world_agents_list". The roster that a world node broadcasts on its rendezvous channel <world peer ID>::ps:rv. The content is {"peers": [...], "update_count": int} and each peer is a dict with id, addrs and misc (the role bits).

CONSOLE_AND_BEHAV_STATUS class-attribute instance-attribute

CONSOLE_AND_BEHAV_STATUS = 'console_and_behav_status'

"console_and_behav_status". The report that a node sends to its inspector. It holds the console of the node, its behavior and the state of that behavior, the profiles of the agents it knows and the properties of the streams it knows.

STATS_UPDATE class-attribute instance-attribute

STATS_UPDATE = 'stats_update'

"stats_update". A batch of statistics that an agent sends to its world. The content is a list of dicts with group_key, stat_name, timestamp (an int) and value (any JSON value). The batch has its own encoding. A send of this type does not count as communication for NodeConn.passed_time_since_last_communication.

STATS_REQUEST class-attribute instance-attribute

STATS_REQUEST = 'stats_request'

"stats_request". A request of an agent for the statistics of its world. As with the other two statistics types, sending it does not count as communication.

STATS_RESPONSE class-attribute instance-attribute

STATS_RESPONSE = 'stats_response'

"stats_response". The answer of a world to a STATS_REQUEST.

The set of the 17 content types above. The constructor accepts a content_type only when it belongs to this set. from_bytes does not check it.

sender property writable

sender: str

The peer ID of the sender (str). The setter turns None into "". P2P.get_messages compares this value with the peer ID that the transport verified and drops the message when the two differ.

content_type property writable

content_type: str

The content type (str). The setter turns None into Msg.MISC and does not check that the value belongs to CONTENT_TYPES.

channel property writable

channel: str

The channel (str). The setter turns None into "<unknown>".

piggyback property writable

piggyback: str

The piggyback string (str). NodeConn.get_messages writes it on the receiver to replace the token with the node ID of the sender. The setter turns None into "".

timestamp_net property writable

timestamp_net: str

The time of creation as a str in the format "%Y-%m-%d %H:%M:%S.%f" (UTC). The setter turns None into "".

content property

content: Any

The content as a Python value. A message without content holds the sentinel string "<empty>". This property has no setter.

to_bytes

to_bytes(streamed_keys: set[str] | None = None) -> bytes
Source code in unaiverse/networking/p2p/messages.py
def to_bytes(self, streamed_keys: set[str] | None = None) -> bytes:
    """Encodes the value object into the protobuf wire format.

    protobuf (and the heavy stream_sample deps) are imported lazily here so the module top stays stdlib-only and
    importable under Pyodide.

    Args:
        streamed_keys: The FILE samples whose file travels next to the message (a file message, Phase 6.5): they
            get their name and MIME type, not their content.

    Returns:
        The wire bytes of the message.
    """
    from . import message_pb2 as pb  # lazy: CPython conn layer only, never under Pyodide

    proto = pb.Message()
    proto.sender = self._sender if self._sender is not None else ""
    proto.timestamp_net = self._timestamp_net if self._timestamp_net is not None else ""
    proto.content_type = self._content_type if self._content_type is not None else self.MISC
    proto.channel = self._channel if self._channel is not None else "<unknown>"
    proto.piggyback = self._piggyback if self._piggyback is not None else ""

    content = self._content
    if content is not None and content != self._EMPTY:

        # Route the content to the correct encoder.
        if self._content_type == Msg.STREAM_SAMPLE:
            self._encode_stream_sample(proto, content, streamed_keys or set())
        elif self._content_type == Msg.STATS_UPDATE:
            self._encode_stats_update(proto, content)
        else:

            # All other structured types use the generic json_content field
            proto.json_content = json.dumps(content)

    return proto.SerializeToString()

Encodes the message in the binary message format and returns the bytes. P2P.send and P2P.broadcast call it in a worker thread because the encoding of tensors and images takes time.

Argument Type Default Meaning
streamed_keys set[str] \| None None The names of the FILE samples whose file travels next to the message (a file message). For them the method writes the file name and the MIME type without the content.

The content goes to one of three encodings.

  • STREAM_SAMPLE: every sample with a non-None data becomes an entry with its data_tag (default -1) and its data_uuid when it is not None. A sample whose data is None is left out. A torch.Tensor is moved to the CPU and made contiguous. Its raw bytes are compressed with gzip at level 1 and travel with its dtype name and its shape. A PIL.Image.Image becomes a PNG at compression level 9. A str is sent as text. A FileContainer is sent with its file name, its MIME type and its content (a str content is encoded to UTF-8) unless its name is in streamed_keys. A data of any other type is left empty.
  • STATS_UPDATE: every dict of the list becomes one entry and its value keeps its JSON type (null, bool, number, string, list or object). A value of another type is sent as its str.
  • Every other type: the content is serialized with json.dumps. A content that JSON cannot represent raises TypeError.

A message without content encodes no content field. The method does not check the size of the result. The native networking library refuses a message above the limits of the peer (see Networking).

from_bytes classmethod

from_bytes(msg_bytes: bytes) -> Msg
Source code in unaiverse/networking/p2p/messages.py
@classmethod
def from_bytes(cls, msg_bytes: bytes) -> 'Msg':
    """Decodes a byte array into a new Msg.

    It builds the value object directly via __new__ (no field validation): a frame off the wire is taken as-is,
    exactly like the previous protobuf-backed path. protobuf is imported lazily.

    Args:
        msg_bytes: The wire bytes.

    Returns:
        The decoded message.
    """
    from . import message_pb2 as pb  # lazy: CPython conn layer only, never under Pyodide

    proto = pb.Message()
    proto.ParseFromString(msg_bytes)

    obj = cls.__new__(cls)
    obj._sender = proto.sender
    obj._timestamp_net = proto.timestamp_net
    obj._content_type = proto.content_type
    obj._channel = proto.channel
    obj._piggyback = proto.piggyback

    payload_type = proto.WhichOneof("content")
    if payload_type == "stream_sample":
        obj._content = cls._decode_stream_sample(proto)
    elif payload_type == "stats_update":
        obj._content = cls._decode_stats_update(proto)
    elif payload_type == "json_content":
        obj._content = json.loads(proto.json_content)
    else:
        obj._content = cls._EMPTY
    return obj

Decodes bytes of the binary message format into a new Msg and returns it. This classmethod is called by P2P.get_messages for every chat frame it pops.

Argument Type Meaning
msg_bytes bytes-like The encoded message. A memoryview is accepted.

The object is built without calling the constructor and therefore skips its checks. A frame from the network is accepted as it is. The content is rebuilt as follows.

  • A stream sample gives the dict of samples. A tensor is decompressed straight into the buffer of a new tensor of the encoded dtype and shape. An image gives a PIL.Image.Image opened lazily on the PNG bytes. A text gives a str and a file gives a FileContainer with its content, file name and MIME type.
  • A statistics batch gives the list of dicts with group_key, stat_name, timestamp and value. A number comes back as a float because the format stores every number as a double.
  • A JSON content gives the result of json.loads.
  • No content gives the sentinel "<empty>".

It raises the parse error of the binary message format for malformed bytes, json.JSONDecodeError for a malformed JSON content and ValueError when the decompressed tensor data do not match the size of its shape and dtype. An unknown dtype name raises AttributeError. P2P.get_messages catches all of them and drops the frame.

attach_received_files

attach_received_files(files: dict[str, str]) -> None
Source code in unaiverse/networking/p2p/messages.py
def attach_received_files(self, files: dict[str, str]) -> None:
    """Gives the FILE samples of a received file message their files, which arrived next to it (Phase 6.5).

    Args:
        files: Sample name -> path of its file, in its place.
    """
    from unaiverse.streams.dataprops import FileContainer
    if self._content_type != Msg.STREAM_SAMPLE or not isinstance(self._content, dict):
        return
    for name, path in files.items():
        sample = self._content.get(name)
        data = sample.get('data') if isinstance(sample, dict) else None
        if isinstance(data, FileContainer):
            sample['data'] = FileContainer(filename=data.filename, mime_type=data.mime_type, path=path)

Attaches to the FILE samples of a received file message the files that arrived with it. P2P.get_messages calls it after place_received_file has moved each file to the downloads folder.

Argument Type Meaning
files dict[str, str] Sample name mapped to the final path of its file.

Each named sample whose data is a FileContainer gets a new FileContainer with the same file name and MIME type and with path pointing to the file. The content stays on disk and is not loaded. Names without a matching FILE sample are ignored. The method changes nothing on a message that is not a stream sample and returns None.