Skip to content

unaiverse.networking.node.connpool

A node is present on two networks at once (see Networking). Any node can get in touch with it on the public network. Only the members of one world share the world network. This module holds the object that manages both networks on behalf of the node. NodeConn owns the two SessionManager objects of the node (one per network) and each manager owns its P2P transport. On top of them NodeConn keeps the pools of connected peers, the roles of the peers in the world, the membership of the world and the bookkeeping of a world join that spans both networks. The source and this page also call it the Coordinator.

Calls always go down one chain. The node calls NodeConn, NodeConn calls the manager of the right network and the manager calls its transport. NodeConn never touches a transport directly.

Node builds the object and hands it to the hosted agent or world as its node_conn attribute. The node calls almost every method. The code of Agent and World calls a few of them through self.node_conn (send, publish, subscribe, unsubscribe, get_role, find_addrs_by_role, is_connected, get_addrs, get_world_node_peer_id, get_last_token, sends_are_queued and get_world_connected_peers_info). A developer who writes an agent normally uses the higher-level methods of Agent and reads node_conn only to inspect the state of the connections.

Three helper objects complete the module. WorldMembership is a frozen snapshot of the members of the world for one cycle. HandoffCorrelation records which public Session yielded the grant that a world Session is redeeming. SendTicket reports the outcome of one direct message sent with NodeConn.send_tracked.

# Inside an action of an agent: send a message and wait until it has left on its stream
ticket = await self.node_conn.send_tracked(peer_id, None, Msg.MISC, {"text": "hello"})
if ticket is None:
    print("the send queue of the peer is full")
elif await ticket.wait(timeout=5.0):
    print("written")
else:
    print(ticket.status, ticket.reason)   # "queued" after a timeout, "dropped" with its reason

WorldMembership module-attribute

WorldMembership = namedtuple('WorldMembership', ['world_agents', 'world_masters', 'world_node_peer_id', 'inspector_peer_id'])

An immutable snapshot of the membership of the world that NodeConn.membership_snapshot builds once per update cycle. It is a namedtuple with four fields.

Field Type Meaning
world_agents frozenset[str] World peer ids of the agents admitted in the world.
world_masters frozenset[str] World peer ids of the masters admitted in the world.
world_node_peer_id str \| None World peer id of the world node that this agent joined (None outside a world and on the world node itself).
inspector_peer_id str \| None Peer id of an inspector admitted to chat with the node (always None in the current version because nothing writes it).

Two readers use the same snapshot within a cycle. The perimeter of the world network cuts every connected peer missing from it (see SessionManager.reconcile). The gate of NodeConn.get_messages accepts chat messages from listed peers not yet in a pool. Because both read the same frozen object, a member added in the middle of a cycle (a pre-admission at grant time) takes effect for both at the next update.

HandoffCorrelation

HandoffCorrelation(is_world_established: Callable[[str], bool], abort_world: Callable, current_world: Callable[[], str | None], clear_world: Callable[[], None])
Source code in unaiverse/networking/node/connpool.py
def __init__(self, is_world_established: Callable[[str], bool], abort_world: Callable,
             current_world: Callable[[], str | None], clear_world: Callable[[], None]) -> None:
    """Initializes an empty correlation, with the hooks it uses to read and change the world state.

    Args:
        is_world_established: Tells whether the world Session to a peer is ESTABLISHED.
        abort_world: Aborts the world Session of a failed handoff.
        current_world: Reads the pool-routing world pointer.
        clear_world: Un-points the pool-routing world pointer.
    """
    self.pending_world_handoff: dict[str, str] = {}
    self.world_to_public: dict[str, str] = {}
    self._is_world_established = is_world_established
    self._abort_world = abort_world
    self._current_world = current_world
    self._clear_world = clear_world

A world join spans two Sessions on two networks (see Joining a world). The agent first gets a grant on its public Session with the world node. It then opens a Session on the world network to the world peer named in the grant and redeems the grant there. Until the world Session is established the public Session stays open as the carrier of the grant. HandoffCorrelation is the ledger of this pair. For each join in flight it maps the public peer id of the carrier to the world peer id of the redemption and back.

The class keeps only the two dictionaries. It acts on the rest of the node only through the callables that its constructor receives. NodeConn and the test suite can therefore share one implementation.

Argument Type Meaning
is_world_established Callable[[str], bool] Tells whether the world Session to a world peer id is ESTABLISHED.
abort_world async Callable[[str], Awaitable] Aborts the world Session of a failed handoff. NodeConn passes a coroutine that calls drop on the world manager.
current_world Callable[[], str \| None] Reads the world peer id that the pools route to (NodeConn.get_world_node_peer_id).
clear_world Callable[[], None] Clears that pointer (NodeConn.set_world(None)).

NodeConn builds one instance in its constructor and drives it through start_world_handoff, rollback_handoff, is_pending_handoff, handoff_carrier_of and complete_world_handoff.

pending_world_handoff instance-attribute

pending_world_handoff: dict[str, str] = {}

The forward index as a dict[str, str] from the public peer id of a carrier to the world peer id of its redemption. It is empty when no join is in flight.

world_to_public instance-attribute

world_to_public: dict[str, str] = {}

The reverse index as a dict[str, str] from the world peer id of a redemption to the public peer id of its carrier. It always holds the pairs of pending_world_handoff in the opposite direction.

start

start(public_peer_id: str, world_peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
def start(self, public_peer_id: str, world_peer_id: str) -> None:
    """Record the correlation at handoff-initiate (both directions)."""
    self.pending_world_handoff[public_peer_id] = world_peer_id
    self.world_to_public[world_peer_id] = public_peer_id

Records a new join in flight in both indexes and returns None. public_peer_id is the world node on the public network and world_peer_id the world node on the world network. An earlier pair with the same keys is overwritten. NodeConn.start_world_handoff calls it.

is_pending

is_pending(world_peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_pending(self, world_peer_id: str) -> bool:
    """True if this world peer-id is the world side of an in-flight handoff."""
    return world_peer_id in self.world_to_public

Returns True when world_peer_id is the world side of a join in flight. The node calls it through NodeConn.is_pending_handoff to distinguish a world Session that redeems a grant from a plain Session between two members of the world.

carrier_of

carrier_of(world_peer_id: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
def carrier_of(self, world_peer_id: str) -> "str | None":
    """The public carrier whose grant opened the handoff to this world peer-id, or
    None when the peer-id is not the world side of an in-flight handoff."""
    return self.world_to_public.get(world_peer_id)

Returns the public peer id of the carrier whose grant opened the join toward world_peer_id. It returns None when that peer is not the world side of a join in flight. The node compares the result with the join it started before it runs the body of the join.

rollback async

rollback(peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
async def rollback(self, peer_id: str) -> None:
    """Roll back the correlation for a terminal Session, whichever side died (async).

    When the PUBLIC carrier dies mid-handoff, the fate of the correlated world
    Session decides everything: already ESTABLISHED -> NO-OP (the join is
    completing; rolling back would strand it half-rolled-back — in-world with
    no world host — and the perimeter would then coercively cut our own host
    with no event, a permanent wedge); still in flight -> pop both indexes AND
    abort the redemption (a dial/handshake left running would complete into a
    headless join). Also un-points the routing pointer when the rolled-back
    world peer is the current one."""
    pending_world = self.pending_world_handoff.get(peer_id)
    if pending_world is not None and self._is_world_established(pending_world):
        return
    world_peer_id = self.pending_world_handoff.pop(peer_id, None)
    if world_peer_id is not None:
        self.world_to_public.pop(world_peer_id, None)
        await self._abort_world(world_peer_id)
    public_peer_id = self.world_to_public.pop(peer_id, None)
    if public_peer_id is not None:
        self.pending_world_handoff.pop(public_peer_id, None)
    rolled_back_world = world_peer_id if world_peer_id is not None else (
        peer_id if public_peer_id is not None else None)
    if rolled_back_world is not None and rolled_back_world == self._current_world():
        self._clear_world()

Undoes the record of a join after one of its two Sessions reached a terminal state (async). peer_id may be either side.

  1. When peer_id is a carrier whose world Session is already ESTABLISHED, nothing happens. The join is completing and its completion removes the entries. A rollback here would leave the agent in the world without a world node and the perimeter would then cut the world node itself.
  2. When peer_id is a carrier whose redemption is still in flight, both entries go away and abort_world is awaited on the world peer id. A dial or a handshake left running would otherwise end in a join that nobody drives.
  3. When peer_id is the world side of a join, both entries go away.
  4. When the rolled back world peer id is the one returned by current_world(), clear_world() runs.

A peer_id missing from both indexes changes nothing. Through NodeConn.rollback_handoff the node calls it on the LOST, FAILED and CLOSED events of either Session.

complete

complete(world_peer_id: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
def complete(self, world_peer_id: str) -> "str | None":
    """Drop the correlation on success. Returns the public carrier's peer-id for
    the caller to retire (GOAWAY on its live transport + pool evict), or None if
    this world peer-id was not part of a handoff."""
    public_peer_id = self.world_to_public.pop(world_peer_id, None)
    if public_peer_id is not None:
        self.pending_world_handoff.pop(public_peer_id, None)
    return public_peer_id

Removes the pair of a successful join and returns the public peer id of its carrier for the caller to retire. It returns None when world_peer_id was not part of a join. NodeConn.complete_world_handoff calls it.

SendTicket

SendTicket(peer_id: str, seq: int | None, status: str = 'queued', reason: str | None = None)
Source code in unaiverse/networking/node/connpool.py
def __init__(self, peer_id: str, seq: int | None, status: str = "queued", reason: str | None = None) -> None:
    """Initializes the ticket.

    Args:
        peer_id: The peer the message was sent to.
        seq: Its sequence number in the send queue of that peer (None when the transport has no queue).
        status: The initial status (default: "queued").
        reason: Why it was dropped, for an initial "dropped" (default: None).
    """
    self.peer_id = peer_id
    self.seq = seq
    self.status = status
    self.reason = reason
    self.progress: tuple[int, int] | None = None  # (bytes written, total) of a message larger than a chunk
    self._done = asyncio.Event()
    if status != "queued":
        self._done.set()

The outcome of one direct message sent with NodeConn.send_tracked. A send only puts the message in the send queue of its peer (see The send queue) and the ticket follows the message until the queue reports its outcome.

Argument Type Default Meaning
peer_id str The peer the message was sent to.
seq int \| None The sequence number of the message in the send queue of that peer. None when the transport has no queues (the browser transport) or when the send failed.
status str "queued" The initial status. Any value other than "queued" makes the ticket final at once.
reason str \| None None Why the message was dropped when the ticket starts as "dropped".

The status moves once from "queued" to one of two final values.

Status Meaning
"queued" The message waits in the queue or is being written.
"written" The whole message left on its stream. This does not prove that the peer processed it (the status of an interaction tells that).
"dropped" The message will never be written. reason is "max_attempts", "max_age", "explicit" or "receiver_stopped" for a dropped queue and the text of the error for a failed send.

NodeConn.pop_send_events resolves the tickets while the network task pops the events of the queues. An action that awaits wait() therefore wakes up only when the node runs its network task and its tick task. In a loop that drives the node with a cycle budget nothing pops the events during the wait and wait() can only time out. Never poll status in a loop without an await.

peer_id instance-attribute

peer_id = peer_id

The peer the message was sent to (str).

seq instance-attribute

seq = seq

The sequence number of the message in the queue of its peer (int). It is None for a ticket that was final at creation.

status instance-attribute

status = status

One of "queued", "written" and "dropped" as in the table above.

reason instance-attribute

reason = reason

Why the message was dropped (str). Every other status leaves it None.

progress instance-attribute

progress: tuple[int, int] | None = None

The progress of a message larger than one chunk as (bytes written, total bytes). The "progress" events of the queue update it. It stays None for a message sent in one frame.

wait async

wait(timeout: float | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
async def wait(self, timeout: float | None = None) -> bool:
    """Waits until the message is written or dropped, for at most timeout seconds (async).

    Args:
        timeout: Seconds to wait (default: Custom.SEND_TICKET_TIMEOUT).

    Returns:
        True if the message was written; False if it was dropped or the time ran out (status says which).
    """
    try:
        await asyncio.wait_for(self._done.wait(), Custom.SEND_TICKET_TIMEOUT if timeout is None else timeout)
    except asyncio.TimeoutError:
        return False
    return self.status == "written"

Waits until the ticket is final or until timeout seconds have passed (async). With timeout=None it waits Custom.SEND_TICKET_TIMEOUT seconds (10 by default). It returns True when the status is "written" and False when the message was dropped or the time ran out. A timeout leaves the ticket "queued". The message may still be written later and status will then show it.

resolve

resolve(status: str, reason: str | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
def resolve(self, status: str, reason: str | None = None) -> None:
    """Sets the final status of the ticket (once: later calls change nothing).

    Args:
        status: "written" or "dropped".
        reason: Why it was dropped (default: None).
    """
    if self.status == "queued":
        self.status, self.reason = status, reason
        self._done.set()

Writes the final status ("written" or "dropped") with its reason and then wakes every wait(). Only the first call changes the ticket because a ticket that is no longer "queued" ignores later calls. NodeConn calls it and the developer never does.

NodeConn

NodeConn(max_connections: int, is_world_node: bool, public_key: str, token: str, local_node_id: str = None)
Source code in unaiverse/networking/node/connpool.py
def __init__(self, max_connections: int,
             is_world_node: bool, public_key: str, token: str,
             local_node_id: str = None) -> None:
    """Initializes a new instance of the NodeConn class.

    The two transport handles are NOT taken here: the constructor builds only the pool
    taxonomy (keyed on the P2P NAMES, which are class constants) and the empty indices.
    The P2P objects arrive later, together with the Node policy, in attach_session_policy,
    which is where they are first used (to build the SessionManagers). A NodeConn before
    attach_session_policy is an inert shell with no transport.

    Args:
        max_connections: The total number of connections the node can handle.
        is_world_node: A boolean flag indicating if this node is a world node.
        public_key: The public key for token verification.
        token: The node's authentication token.
        local_node_id: this node's application node-id, used when building the
            per-instance SessionManagers in attach_session_policy.
    """
    self._init_pools(max_connections=max_connections,
                     valid_p2p_names={NodeConn.P2P_PUBLIC, NodeConn.P2P_WORLD},
                     pool_name_to_p2p_name_and_ratio={
                         NodeConn.IN_PUBLIC: [NodeConn.P2P_PUBLIC, 0.25 / 2. if not is_world_node else 0.25 / 2.],
                         NodeConn.OUT_PUBLIC: [NodeConn.P2P_PUBLIC, 0.25 / 2. if not is_world_node else 0.25 / 2.],
                         NodeConn.IN_WORLD_AGENTS: [NodeConn.P2P_WORLD, .75 / 2. if not is_world_node else 0.5 / 2],
                         NodeConn.OUT_WORLD_AGENTS: [NodeConn.P2P_WORLD, .75 / 2 if not is_world_node else 0.5 / 2],
                         NodeConn.IN_WORLD_NODE: [NodeConn.P2P_WORLD, 0. if not is_world_node else -1.],
                         NodeConn.OUT_WORLD_NODE: [NodeConn.P2P_WORLD, 0. if not is_world_node else -1.],
                         NodeConn.IN_WORLD_MASTERS: [NodeConn.P2P_WORLD, 0. if not is_world_node else 0.25 / 2.],
                         NodeConn.OUT_WORLD_MASTERS: [NodeConn.P2P_WORLD, 0. if not is_world_node else 0.25 / 2.]
                     },
                     public_key=public_key, token=token)

    # The pure world membership (world_agents_set / world_masters_set /
    # world_node_peer_id) now lives in sm_world, next to the Sessions it gates (built
    # in attach_session_policy); the Coordinator reads it back through
    # membership_snapshot(). inspector_peer_id stays here: it is not pure world
    # membership but an orthogonal, currently-inert chat exception.
    self.inspector_peer_id = None

    # role_to_peer_ids and peer_id_to_addrs stay Coordinator-owned and do NOT descend
    # into sm_world with the world membership. role_to_peer_ids is the inverse
    # index of peer_id_to_misc (the global cross-pool taxonomy, kept here) and set_role
    # updates both together; find_addrs_by_role reads role_to_peer_ids and
    # peer_id_to_addrs jointly, and get_addrs feeds the dial path. Only the pure world
    # membership (the two sets + world_node_peer_id, now in sm_world) is what the
    # perimeter classifies against.
    self.role_to_peer_ids = {}
    self.peer_id_to_addrs = {}

    # The per-cycle world-membership snapshot, frozen at the start of each update()
    # and read by BOTH the perimeter (via _reconcile_instance) and the chat-admission
    # gate in get_messages, so the two views never diverge inside a cycle. A roster
    # mutation written mid-cycle (pre-admission) takes effect only at the next
    # update()'s snapshot, for both views. Bootstrapped to an explicit empty snapshot
    # so get_messages admits no not-yet-connected peer before the first update(): the
    # roster lives in sm_world, built later in attach_session_policy, so there is no
    # manager to snapshot from yet.
    self._cycle_membership = WorldMembership(
        world_agents=frozenset(), world_masters=frozenset(),
        world_node_peer_id=None, inspector_peer_id=None,
    )

    # Rendezvous
    self.rendezvous_tag = -1

    # Joiner: while the dials toward the other members wait for a roster that lists us,
    # the grant tag that roster must be newer than (None when not waiting), the end of
    # the wait, and the peers whose dial is held.
    self._roster_wait_tag: int | None = None
    self._roster_wait_until = 0.0
    self._held_world_dials: set[str] = set()

    # Pre-admissions still waiting for their world-side redemption: peer_id →
    # monotonic deadline. Written by the grant-time pre-admission
    # (add_to_world_*_list with provisional_ttl_s), cleared by the world-side
    # registration (same writers, no TTL) or by remove_from_world_lists; the
    # host sweeps the expired ones each cycle, so a grant that is never
    # redeemed does not leave a ghost member in the roster.
    self.world_preadmissions: dict[str, float] = {}

    # Application node-id, used when this Coordinator builds the SessionManagers.
    self._local_node_id = local_node_id

    # Per-instance SessionManagers. The Coordinator owns them: it builds both in
    # attach_session_policy (once the Node policy is available) and consults them
    # so the hosted entity (which holds conn, not the managers) can ask about
    # per-peer Session state (see is_peer_session_pending).
    self._sm_public = None
    self._sm_world = None
    self._session_managers = []

    # Refusals of a full send queue, per peer: logged as a warning at most once per interval, with their count
    self._refused_sends: dict[str, list] = {}  # Peer ID -> [refusals not logged yet, time of the last log]

    # Tracked sends (send_tracked), per (instance, peer): the tickets still queued, and what the send events said
    # so far, for a ticket whose events were popped while its send was still returning its sequence number
    self._tickets: dict[tuple[str, str], dict[int, SendTicket]] = {}
    self._written_upto: dict[tuple[str, str], int] = {}
    self._recent_drops: dict[tuple[str, str], list[tuple[int, int, str]]] = {}

    # World-handoff correlation, owned here so it sits next to the two SessionManagers
    # it spans. The ledger itself (the twin maps + start/rollback/complete) lives in
    # HandoffCorrelation, shared with the test-harness mirror; the effect callables
    # close over self so they see the managers wired later by attach_session_policy.
    # Node drives the handoff through the start/rollback/complete facades below.
    self._handoff = HandoffCorrelation(
        is_world_established=lambda wpid: (self._sm_world is not None
                                           and self._sm_world.is_established(wpid)),
        abort_world=self._abort_world_redemption,
        current_world=self.get_world_node_peer_id,
        clear_world=lambda: self.set_world(None),
    )

The networking Coordinator of a node. Node builds it as soon as it knows its profile and attaches the two transports later with attach_session_policy. Before that call the object has no transport and no manager and most of its methods fail because the manager is None.

Argument Type Default Meaning
max_connections int Total number of peers the pools can hold. The node passes the max_connections of its profile. It must be at least 8 (one per pool).
is_world_node bool True for the node of a world. It changes the capacity of each pool (see below).
public_key str Public key of the UNaIVERSE server that verifies the tokens of the peers (see tokens). With None no token is ever accepted.
token str The token of this node that every chat message it sends carries. set_token replaces it after a refresh.
local_node_id str None The node id of this node that the two managers receive.

Pools

A pool is a set of peer ids connected to this node in one direction on one network and in one role. A connected peer is in at most one pool. There are eight pools. The name of each pool joins a direction prefix (in_ or out_), a group and a network suffix (_public or _private).

Constant Value Network Holds
IN_PUBLIC "in_all_unaiverse_public" public peers that dialed this node
OUT_PUBLIC "out_all_unaiverse_public" public peers this node dialed
IN_WORLD_AGENTS "in_world_agents_private" world agents of the world that dialed this node
OUT_WORLD_AGENTS "out_world_agents_private" world agents of the world this node dialed
IN_WORLD_NODE "in_world_node_private" world the world node when it dialed this agent
OUT_WORLD_NODE "out_world_node_private" world the world node when this agent dialed it
IN_WORLD_MASTERS "in_world_masters_private" world masters of the world that dialed this node
OUT_WORLD_MASTERS "out_world_masters_private" world masters of the world this node dialed

Each pool has a fixed capacity that the constructor computes once from max_connections and a ratio per pool. The ratios differ for an agent and for a world node.

Pool Ratio for an agent Ratio for a world node
IN_PUBLIC, OUT_PUBLIC 0.125 each 0.125 each
IN_WORLD_AGENTS, OUT_WORLD_AGENTS 0.375 each 0.25 each
IN_WORLD_NODE, OUT_WORLD_NODE 0 each -1 each
IN_WORLD_MASTERS, OUT_WORLD_MASTERS 0 each 0.125 each

Let Z be the number of pools with ratio 0. A pool with a ratio of 0 or more gets max(floor(ratio * (max_connections - Z)), 1) places and a pool with a negative ratio gets none. The places left over by the rounding go to the last pool (OUT_WORLD_MASTERS). With max_connections=100 an agent gets 12 places in each public pool, 36 in each world agent pool and one in each of the four other pools. With the same value a world node gets 12 and 12 public places, 25 and 25 world agent places, no world node place and 12 and 14 master places. The constructor raises AssertionError when the positive ratios do not sum to 1.0 or when max_connections cannot give every pool its minimum.

The constructor creates the attributes below in the same step as the capacities. They have no entry of their own on this page.

Attribute Type Meaning
max_con int The max_connections given to the constructor.
pool_count, pool_names, pool_ratios int, list[str], list[float] The number of pools with their names in the order above and their ratios.
pool_name_to_pool_triple dict[str, list] For each pool the list [set of peer ids, capacity, SessionManager of its network]. The manager is None until set_session_managers runs.
pool_name_to_peer_infos dict[str, dict[str, dict]] For each pool the peer info of each peer (id, addrs, direction, misc and what the transport reports).
peer_id_to_pool_name dict[str, str] The pool of each connected peer. It is the index behind is_connected, get_pool_of and the chat gate.
peer_id_to_misc dict[str, int] The role bits of each known peer (see get_role). They survive the removal of a peer from its pool.
peer_id_to_token dict[str, str] The last valid token received from each peer in a pool.
pool_name_to_added_in_last_update, pool_name_to_removed_in_last_update dict[str, set[str]] The pool changes of the last update for the pools that changed.

P2P_PUBLIC class-attribute instance-attribute

P2P_PUBLIC = 'p2p_public'

The name of the public network ("p2p_public"). Every manager, transport, Session and Session event carries it as p2p_name.

P2P_WORLD class-attribute instance-attribute

P2P_WORLD = 'p2p_world'

The name of the world network ("p2p_world").

IN_PUBLIC class-attribute instance-attribute

IN_PUBLIC = __INBOUND + __ALL_UNAIVERSE + __PUBLIC_NET

Name of the pool of the public peers that dialed this node (see the table of the pools).

OUT_PUBLIC class-attribute instance-attribute

OUT_PUBLIC = __OUTBOUND + __ALL_UNAIVERSE + __PUBLIC_NET

Name of the pool of the public peers that this node dialed.

IN_WORLD_AGENTS class-attribute instance-attribute

IN_WORLD_AGENTS = __INBOUND + __WORLD_AGENTS_ONLY + __PRIVATE_NET

Name of the pool of the world agents that dialed this node.

OUT_WORLD_AGENTS class-attribute instance-attribute

OUT_WORLD_AGENTS = __OUTBOUND + __WORLD_AGENTS_ONLY + __PRIVATE_NET

Name of the pool of the world agents that this node dialed.

IN_WORLD_NODE class-attribute instance-attribute

IN_WORLD_NODE = __INBOUND + __WORLD_NODE_ONLY + __PRIVATE_NET

Name of the pool of the world node when it dialed this agent. Its capacity is 0 on a world node.

OUT_WORLD_NODE class-attribute instance-attribute

OUT_WORLD_NODE = __OUTBOUND + __WORLD_NODE_ONLY + __PRIVATE_NET

Name of the pool of the world node when this agent dialed it. Its capacity is 0 on a world node.

IN_WORLD_MASTERS class-attribute instance-attribute

IN_WORLD_MASTERS = __INBOUND + __WORLD_MASTERS_ONLY + __PRIVATE_NET

Name of the pool of the world masters that dialed this node.

OUT_WORLD_MASTERS class-attribute instance-attribute

OUT_WORLD_MASTERS = __OUTBOUND + __WORLD_MASTERS_ONLY + __PRIVATE_NET

Name of the pool of the world masters that this node dialed.

PUBLIC class-attribute instance-attribute

PUBLIC = {IN_PUBLIC, OUT_PUBLIC}

The set {IN_PUBLIC, OUT_PUBLIC}. Every method that takes pool_names accepts it as it accepts the other aggregates below.

WORLD_NODE class-attribute instance-attribute

WORLD_NODE = {IN_WORLD_NODE, OUT_WORLD_NODE}

The set {IN_WORLD_NODE, OUT_WORLD_NODE}.

WORLD_AGENTS class-attribute instance-attribute

The set {IN_WORLD_AGENTS, OUT_WORLD_AGENTS}.

WORLD_MASTERS class-attribute instance-attribute

The set {IN_WORLD_MASTERS, OUT_WORLD_MASTERS}.

WORLD class-attribute instance-attribute

The six pools of the world network (WORLD_NODE | WORLD_AGENTS | WORLD_MASTERS).

ALL class-attribute instance-attribute

ALL = PUBLIC | WORLD

All eight pools (PUBLIC | WORLD).

OUTGOING class-attribute instance-attribute

The four out_ pools that hold the peers this node dialed.

INCOMING class-attribute instance-attribute

The four in_ pools that hold the peers that dialed this node.

inspector_peer_id instance-attribute

inspector_peer_id = None

Peer id of an inspector that may chat with this node without being a world member. In the current version nothing writes it and it stays None. membership_snapshot copies it into every WorldMembership.

role_to_peer_ids instance-attribute

role_to_peer_ids = {}

The inverse of peer_id_to_misc as a dict[int, set[str]] from a role value to the peer ids that hold it. set_role keeps the two in sync. find_addrs_by_role and count_by_role read it.

peer_id_to_addrs instance-attribute

peer_id_to_addrs = {}

The addresses of the world peers as a dict[str, list[str]]. The methods that write the roster (set_world_agents_list, add_to_world_agents_list and their counterparts for the masters) fill it. get_addrs reads it and update passes it to the world manager as the list of known peers.

rendezvous_tag instance-attribute

rendezvous_tag = -1

The update_count of the last roster that this node read from the rendezvous of the world (int, -1 before the first one). set_world_agents_and_world_masters_lists_from_rendezvous ignores every roster whose count is not larger. A world node also writes it directly when it publishes a roster.

world_preadmissions instance-attribute

world_preadmissions: dict[str, float] = {}

On a world node it maps the world peer id of each joiner that received a grant and has not yet redeemed it to a deadline in time.monotonic() seconds. add_to_world_agents_list and add_to_world_masters_list with provisional_ttl_s write an entry. The same calls without that argument remove it and so does remove_from_world_lists. sweep_world_preadmissions drops the expired entries.

Identity of the node

public_peer_id property

public_peer_id: str | None

The peer id of this node on the public network (str) as the public manager holds it. Before attach_session_policy it raises AttributeError.

world_peer_id property

world_peer_id: str | None

The peer id of this node on the world network. It identifies this node and not the world node it joined (that one is get_world_node_peer_id()).

public_addresses property

public_addresses: list[str]

The addresses on which this node is reachable on the public network (list[str]). Each access reads them live from the transport and an empty list means that the transport could not answer.

world_addresses property

world_addresses: list[str]

The addresses of this node on the world network. Each access reads them live like public_addresses.

world_is_public property

world_is_public: bool | None

Whether the transport currently judges the world network of this node reachable from the internet (bool, None before a verdict). The node reads it together with world_relay_enabled to decide whether a world can offer its own relay (see Relays).

world_relay_enabled property

world_relay_enabled: bool

Whether the relay client is enabled on the world network (bool).

get_world_connected_peers_info

get_world_connected_peers_info() -> list | None
Source code in unaiverse/networking/node/connpool.py
def get_world_connected_peers_info(self) -> list | None:
    """Raw transport-level connected peers on the world instance, for the stats path
    (Agent.collect_and_store_own_stats). Reads through the world manager as internal
    custody and returns the data, not the handle, so callers stop reaching into the P2P.
    None on an FFI error (transport state unknown): callers must skip, not treat it as
    zero peers, or a transient failure poisons the stats with a false empty sample."""
    return self._sm_world.connected_peers_info()

Returns the peer infos of every peer that the transport sees connected to the world network whether or not it is in a pool. A None return means that the transport could not answer. The caller must then skip its work and never read the None as "no peers". Agent.collect_and_store_own_stats reads it to compute the statistics of an agent.

Tokens

set_token

set_token(token: str) -> None
Source code in unaiverse/networking/node/connpool.py
def set_token(self, token: str) -> None:
    """Sets the authentication token for the connection pools.

    Args:
        token: The new token string.
    """
    self.__token = token

Replaces the token of this node in every chat message sent from now on. The node calls it after each refresh of its token. The Sessions read the token through their own factory and push the new one to their peers on the next tick (see SessionManager.tick).

verify_token async

verify_token(token: str, peer_id: str) -> tuple[str | None, str | None]
Source code in unaiverse/networking/node/connpool.py
async def verify_token(self, token: str, peer_id: str) -> tuple[str | None, str | None]:
    """Verifies a received token using the provided public key (async).

    Args:
        token: The token string to verify.
        peer_id: The peer ID associated with the token.

    Returns:
        A tuple containing the node ID and CV hash if the token is valid, otherwise None.
    """
    if self.__token_verifier is None:
        return None, None
    else:
        node_id, cv_hash = self.__token_verifier.verify_token(token, p2p_peer=peer_id)
        return node_id, cv_hash  # If the verification fails, this is None, None

Verifies the token of a peer with the public key given to the constructor (async). The token must carry the signature of the UNaIVERSE server, must not be expired and must list peer_id among its peer ids. On success it returns (node_id, cv_hash) from the token. On failure and when the constructor received no public key it returns (None, None). get_messages calls it on every chat message.

verify_token_claims async

verify_token_claims(token: str, peer_id: str) -> tuple
Source code in unaiverse/networking/node/connpool.py
async def verify_token_claims(self, token: str, peer_id: str) -> tuple:
    """Verify a token and return the full claims, including the root-attested
    `p2p_peers` binding, for the Session handshake (RT). The `p2p_peer` check is
    always against `peer_id` (the transport-verified peer-id of the speaker) (async).

    Returns:
        ``(node_id, cv_hash, p2p_peers, exp, code_hash)`` on success,
        ``(None, None, (), 0, None)`` on failure or when no verifier is configured.
    """
    if self.__token_verifier is None:
        return None, None, (), 0, None
    return self.__token_verifier.verify_token_claims(token, p2p_peer=peer_id)

Verifies a token like verify_token and returns all of its claims as (node_id, cv_hash, p2p_peers, exp, code_hash) (async). A failure returns (None, None, (), 0, None). p2p_peers is the tuple of the peer ids of the node on both networks, exp the expiry in Unix seconds and code_hash the hash of the stored code of a world (None for an agent). attach_session_policy hands this method to both managers as their token verifier. Every Session calls it during its handshake and on each token update (see Session).

Pool bookkeeping

add

add(peer_info: dict, pool_name: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def add(self, peer_info: dict, pool_name: str) -> bool:
    """Adds a connected peer to a specified connection pool.

    Args:
        peer_info: A dictionary containing information about the peer.
        pool_name: The name of the pool to add the peer to.

    Returns:
        True if the peer is successfully added, otherwise False.
    """
    peer_id = peer_info['id']
    pool, max_size, _ = self.pool_name_to_pool_triple[pool_name]
    if len(pool) < max_size:

        # "hoping" peer IDs are unique, and stopping duplicate cases
        if peer_id in self.peer_id_to_pool_name and self.peer_id_to_pool_name[peer_id] != pool_name:
            return False

        self.peer_id_to_pool_name[peer_id] = pool_name

        # Setting 'misc' field (default is 0, where 0 means public)
        peer_info['misc'] = self.peer_id_to_misc.get(peer_id, 0)

        # Storing (only)
        pool.add(peer_id)
        self.pool_name_to_peer_infos[pool_name][peer_id] = peer_info
        return True
    else:
        return False

Puts a connected peer in a pool. peer_info must have an id key. It returns False when the pool is full or when the peer is already in another pool and True otherwise. On success it writes the role bits of the peer (0 when unknown) into peer_info["misc"] and stores the dictionary itself without copying it. Only update calls it.

drop_peer async

drop_peer(peer_id: str, reason: int | None = None, settled: bool = False) -> list
Source code in unaiverse/networking/node/connpool.py
async def drop_peer(self, peer_id: str, reason: int | None = None,
                    settled: bool = False) -> list:
    """Voluntary per-peer teardown, the single teardown verb the hosted entity
    drives through (Node.__purge): ``sm.drop`` on the owning instance + the pool
    eviction. What happens to the Session and the transport is the manager's
    state dispatch (see SessionManager.drop): a live established Session with a
    reason is GOAWAY-closed only, and the transport falls with the deferred
    settlement cut once the CLOSED lands — never a disconnect in the same stack
    as the farewell write, which would destroy the GOAWAY on the wire; the
    coercive branches (mid-handshake, reasonless on a live Session, KNOWN,
    sessionless) abort/forget and sever the transport inline (async).

    Returns the SessionEvents for Node to dispatch (always ``[]`` today: the
    CLOSED arrives later via GOAWAY-ACK / the CLOSING timeout). The grace case
    (transport drop with a surviving RECONNECTING Session) does NOT come through
    here: it is handled by ``on_peer_disconnected``, which syncs the pool without
    closing the Session.

    The owning manager is resolved BEFORE the pool eviction (the pool index feeds
    ``_sm_of``'s fallback); a peer unknown to both registries is a no-op, which
    tolerates the frequent double-purge (a CLOSED dispatched after an earlier
    purge — also a no-op inside sm.drop, on the tearing-down branch).

    Args:
        peer_id: The peer ID to tear down.
        reason: Optional ReasonCode; when set and the Session is closable, it is
            GOAWAY-closed with it.
        settled: True for the RECKONING purge of a terminal SessionEvent (or of
            the polled transport drop): the SM settlement already handled the
            Session and scheduled/executed the transport cut, so only the pool
            bookkeeping is evicted here — sm.drop is skipped entirely. This is
            what keeps the reckoning from touching a SUCCESSOR Session born in
            the same pump batch (the settled relation's teardown must never
            leak onto the fresh one that replaced it).

    Returns:
        The list of SessionEvents to dispatch.
    """
    sm = self._sm_of(peer_id)
    if not settled:
        events = await sm.drop(peer_id, reason) if sm is not None else []
    else:
        events = []

    # What is still queued for the peer goes too, so that its writer never dials it again. Not while a GOAWAY is
    # in flight: the messages sent just before the purge still leave on the live link, and the settled purge that
    # follows the CLOSED drops whatever is left
    if sm is not None and (settled or not sm.is_tearing_down(peer_id)):
        dropped = sm.drop_send_queue(peer_id)
        if dropped > 0:
            log.network(f"Dropped {dropped} queued messages to purged peer {peer_id}", sub=sm.log_sub)
    self._refused_sends.pop(peer_id, None)
    self._evict_from_pools(peer_id)
    return events

Tears down the relation with one peer on the network of that peer and removes it from the pools (async). The node purges a peer only through this method.

Argument Type Default Meaning
peer_id str The peer.
reason int \| None None A reason code of sess_msg. With a reason a live Session receives a GOAWAY and closes. Without one it is aborted at once.
settled bool False True when the Session has already ended and its manager has already scheduled the cut of its connection. The method then leaves the Session untouched and only changes the pools.

With settled=False it calls SessionManager.drop on the manager of the peer (see its table of cases). Then it empties the send queue of the peer unless a GOAWAY is still in flight. In that case the messages sent just before the purge can still go out on the live link. The settled purge that follows the CLOSED event drops what remains. The method finally removes the peer from its pool. For a peer unknown to every manager and every pool the call does nothing. The return value is always an empty list because the CLOSED event comes later. The flag settled prevents the teardown of an old Session from touching a new Session with the same peer created in the same pump.

get_pool_status

get_pool_status() -> dict[str, set]
Source code in unaiverse/networking/node/connpool.py
def get_pool_status(self) -> dict[str, set]:
    """Returns a dictionary showing the set of peer IDs in each pool.

    Args:
        None.

    Returns:
        A dictionary mapping pool names to the set of peer IDs in that pool.
    """
    return {k: v[0] for k, v in self.pool_name_to_pool_triple.items()}

Returns a dict[str, set[str]] from each pool name to its set of peer ids. The sets are the live ones and not copies.

get_all_connected_peer_ids

get_all_connected_peer_ids() -> list[str]
Source code in unaiverse/networking/node/connpool.py
def get_all_connected_peer_ids(self) -> list[str]:
    """Retrieves a list of all peer IDs currently connected across all pools.

    Args:
        None.

    Returns:
        A list of all connected peer IDs.
    """
    return list(self.peer_id_to_pool_name.keys())

Returns the list of the peer ids in every pool.

get_last_token

get_last_token(peer_id: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
def get_last_token(self, peer_id: str) -> str | None:
    """Retrieves the last known token for a given peer.

    Args:
        peer_id: The peer ID to query.

    Returns:
        The token string if found, otherwise None.
    """
    return self.peer_id_to_token[peer_id] if peer_id in self.peer_id_to_token else None

Returns the last valid token received from a peer in a pool and None when there is none. The world node reads it to check the identity behind a chat message.

get_pool_of

get_pool_of(peer_id: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
def get_pool_of(self, peer_id: str) -> str | None:
    """Gets the pool name for a given connected peer.

    Args:
        peer_id: The peer ID to query.

    Returns:
        The name of the pool the peer is in.
    """
    if peer_id in self.peer_id_to_pool_name:
        return self.peer_id_to_pool_name[peer_id]
    else:
        return None

Returns the name of the pool of a peer. A peer in no pool gives None.

size

size(pool_names: list[str] | None = None) -> int
Source code in unaiverse/networking/node/connpool.py
def size(self, pool_names: list[str] | None = None) -> int:
    """Returns the total number of connections across all specified pools.

    Args:
        pool_names: A list of pool names to sum the size of. If None, returns the total size of all pools.

    Returns:
        The total number of connections.
    """
    if pool_names is None:
        c = 0
        for v in self.pool_name_to_pool_triple.values():
            c += len(v[0])
        return c
    else:
        c = 0
        for p in pool_names:
            c += len(self.pool_name_to_pool_triple[p][0])
        return c

Returns the number of peers in the given pools. With pool_names=None it counts all pools. An unknown pool name raises KeyError.

is_connected

is_connected(peer_id: str, pool_names: list[str] | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_connected(self, peer_id: str, pool_names: list[str] | None = None) -> bool:
    """Checks if a peer is connected in any of the specified pools.

    Args:
        peer_id: The peer ID to check.
        pool_names: A list of pool names to search within. If None, searches all pools.

    Returns:
        True if the peer is found in any of the pools, otherwise False.
    """
    if pool_names is None:
        return peer_id in self.peer_id_to_pool_name
    else:
        for p in pool_names:
            if peer_id in self.peer_id_to_pool_name and p == self.peer_id_to_pool_name[peer_id]:
                return True
        return False

Returns True when the peer is in one of the given pools. With pool_names=None any pool counts.

in_connection_queues

in_connection_queues(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def in_connection_queues(self, peer_id: str) -> bool:
    """Checks if a peer ID exists in any connection pool.

    Args:
        peer_id: The peer ID to check.

    Returns:
        True if the peer is found in any pool, otherwise False.
    """
    return peer_id in self.peer_id_to_pool_name

Returns True when the peer is in any pool. It is equivalent to is_connected(peer_id).

is_public

is_public(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_public(self, peer_id: str) -> bool:
    """Checks if a peer is connected via the public network.

    Args:
        peer_id: The peer ID to check.

    Returns:
        True if the peer is in a public pool, otherwise False.
    """
    pool_name = self.get_pool_of(peer_id)
    return pool_name in NodeConn.PUBLIC

Returns True when the pool of the peer is one of PUBLIC. This method concerns a remote peer and has nothing to do with the reachability of this node (world_is_public).

is_world_master

is_world_master(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_world_master(self, peer_id: str) -> bool:
    """Checks if a peer is a world master.

    Args:
        peer_id: The peer ID to check.

    Returns:
        True if the peer is in a world master pool, otherwise False.
    """
    pool_name = self.get_pool_of(peer_id)
    return pool_name in NodeConn.WORLD_MASTERS

Returns True when the pool of the peer is one of WORLD_MASTERS.

is_world_node

is_world_node(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_world_node(self, peer_id: str) -> bool:
    """Checks if a peer is the world node.

    Args:
        peer_id: The peer ID to check.

    Returns:
        True if the peer is in a world node pool, otherwise False.
    """
    pool_name = self.get_pool_of(peer_id)
    return pool_name in NodeConn.WORLD_NODE

Returns True when the pool of the peer is one of WORLD_NODE.

is_in_world

is_in_world(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_in_world(self, peer_id: str) -> bool:
    """Checks if a peer is connected to the world network.

    Args:
        peer_id: The peer ID to check.

    Returns:
        True if the peer is in any world pool, otherwise False.
    """
    pool_name = self.get_pool_of(peer_id)
    return pool_name in NodeConn.WORLD

Returns True when the pool of the peer is one of WORLD.

get_all_connected_peer_infos

get_all_connected_peer_infos(pool_names: list[str] | set[str]) -> list[dict]
Source code in unaiverse/networking/node/connpool.py
def get_all_connected_peer_infos(self, pool_names: list[str] | set[str]) -> list[dict]:
    """Retrieves a list of all peer info dictionaries for the specified pools.

    Args:
        pool_names: A list or set of pool names to query.

    Returns:
        A list of dictionaries containing peer information.
    """
    ret = []
    for p in pool_names:
        ret += list(self.pool_name_to_peer_infos[p].values())
    return ret

Returns the peer info dictionaries of every peer in the given pools (a list or set of pool names). The dictionaries are the stored ones and a change to them changes the pools.

get_added_after_updating

get_added_after_updating(pool_names: list[str] | None = None) -> dict[str, set] | set
Source code in unaiverse/networking/node/connpool.py
def get_added_after_updating(self, pool_names: list[str] | None = None) -> dict[str, set] | set:
    """Retrieves the set of peers added after the last update cycle for specified pools.

    Args:
        pool_names: A list of pool names to check. If None, returns the per-pool mapping.

    Returns:
        A dictionary mapping pool names to sets of added peer IDs, or the full per-pool
        mapping when no pool names are given.
    """
    if pool_names is not None:
        ret = {}
        for p in pool_names:
            ret[p] = self.pool_name_to_added_in_last_update[p]
        return ret
    else:
        return self.pool_name_to_added_in_last_update

Returns the peers that the last update put in the pools. With pool_names=None it returns the whole mapping of the pools that changed. With a list of names it builds a new dictionary for those names and raises KeyError for any name unchanged in the last update. The node reads the return value of update instead.

get_removed_after_updating

get_removed_after_updating(pool_names: list[str] | None = None) -> dict[str, set] | set
Source code in unaiverse/networking/node/connpool.py
def get_removed_after_updating(self, pool_names: list[str] | None = None) -> dict[str, set] | set:
    """Retrieves the set of peers removed after the last update cycle for specified pools.

    Args:
        pool_names: A list of pool names to check. If None, returns the per-pool mapping.

    Returns:
        A dictionary mapping pool names to sets of removed peer IDs, or the full per-pool
        mapping when no pool names are given.
    """
    if pool_names is not None:
        ret = {}
        for p in pool_names:
            ret[p] = self.pool_name_to_removed_in_last_update[p]
        return ret
    else:
        return self.pool_name_to_removed_in_last_update

Returns the peers that the last update found missing from the pools. It behaves like get_added_after_updating (KeyError included).

Roles and the world roster

The role of a peer is an int of bits called misc. The value 0 means a public peer. Bit 0 (value 1) marks a member of the world and bit 1 (value 2) a master. The bits from 2 upward encode the role name assigned by the world. An agent of the world therefore has misc & 3 == 1 and a master has misc & 3 == 3.

The members of the world live in the world manager (SessionManager.world_agents_set, world_masters_set and world_node_peer_id) next to the Sessions whose admission they control. Only the methods below change them and the node never writes these sets directly.

get_role

get_role(peer_id: str) -> int
Source code in unaiverse/networking/node/connpool.py
def get_role(self, peer_id: str) -> int:
    """Retrieves the role of a given peer.

    Args:
        peer_id: The peer ID to query.

    Returns:
        The integer role of the peer.
    """
    role = self.peer_id_to_misc.get(peer_id, 0)  # 0 means public
    assert role >= 0, "Expecting role to be >= 0"
    assert role & 1 != 0 or role == 0, "Expecting public role to be zero (all-zero-bits)"
    return role

Returns the role bits of a peer and 0 for an unknown peer. A stored value that is negative or that has higher bits without bit 0 raises AssertionError.

set_role

set_role(peer_id: str, new_role: int) -> None
Source code in unaiverse/networking/node/connpool.py
def set_role(self, peer_id: str, new_role: int) -> None:
    """Updates the role of a peer and its associated role-based lists.

    Args:
        peer_id: The peer ID to update.
        new_role: The new role for the peer.
    """
    cur_role = self.get_role(peer_id)

    # Updating
    self.peer_id_to_misc[peer_id] = new_role

    if self.in_connection_queues(peer_id):
        pool_name = self.get_pool_of(peer_id)
        assert pool_name is not None
        self.pool_name_to_peer_infos[pool_name][peer_id]['misc'] = new_role

    # Updating
    if cur_role in self.role_to_peer_ids:
        if peer_id in self.role_to_peer_ids[cur_role]:
            self.role_to_peer_ids[cur_role].remove(peer_id)
        if len(self.role_to_peer_ids[cur_role]) == 0:
            del self.role_to_peer_ids[cur_role]
    if new_role not in self.role_to_peer_ids:
        self.role_to_peer_ids[new_role] = set()
    self.role_to_peer_ids[new_role].add(peer_id)

Writes a new role for a peer into peer_id_to_misc, into the misc field of its peer info when the peer is in a pool and into role_to_peer_ids. In role_to_peer_ids it moves the peer from the set of the old role to the set of the new one and deletes an emptied old set. The node calls it when a world assigns or changes a role.

get_addrs

get_addrs(peer_id: str) -> list[str] | None
Source code in unaiverse/networking/node/connpool.py
def get_addrs(self, peer_id: str) -> list[str] | None:
    """Retrieves the list of addresses for a given peer.

    Args:
        peer_id: The peer ID to query.

    Returns:
        A list of addresses for the peer.
    """
    if peer_id in self.peer_id_to_addrs:
        return self.peer_id_to_addrs.get(peer_id)
    else:
        return None

Returns the addresses of a world peer from peer_id_to_addrs. An unknown peer gives None.

set_addresses_in_peer_info

set_addresses_in_peer_info(peer_id: str, addresses: list[str]) -> None
Source code in unaiverse/networking/node/connpool.py
def set_addresses_in_peer_info(self, peer_id: str, addresses: list[str]) -> None:
    """Updates the list of addresses for a given peer.

    Args:
        peer_id: The peer ID to update.
        addresses: A new list of addresses for the peer.
    """
    if self.in_connection_queues(peer_id):
        pool_name = self.get_pool_of(peer_id)
        assert pool_name is not None
        addrs = self.pool_name_to_peer_infos[pool_name][peer_id]['addrs']
        addrs.clear()  # Warning: do not allocate a new list, keep the current one (it is referenced by others)
        for _addrs in addresses:
            addrs.append(_addrs)

Replaces the addresses in the peer info of a peer in a pool with addresses. Other structures hold a reference to the list object and the method therefore empties and refills it in place. A peer in no pool is ignored. The node calls it when a peer announces new addresses.

find_addrs_by_role

find_addrs_by_role(role: int, return_peer_ids_too: bool = False, discard_yourself: bool = False) -> list | tuple[list, list]
Source code in unaiverse/networking/node/connpool.py
def find_addrs_by_role(self, role: int, return_peer_ids_too: bool = False,
                       discard_yourself: bool = False) -> list | tuple[list, list]:
    """Finds all addresses of peers with a specific role.

    Args:
        role: The integer role to search for.
        return_peer_ids_too: A boolean to also return the peer IDs.
        discard_yourself: True to avoid reporting your info on the returned data.

    Returns:
        A list of lists of addresses, and optionally a list of peer IDs.
    """
    if role in self.role_to_peer_ids:
        peer_ids = self.role_to_peer_ids[role]
    else:
        if not return_peer_ids_too:
            return []
        else:
            return [], []
    ret_addrs = []
    ret_peer_ids = []
    for peer_id in peer_ids:
        if discard_yourself and (peer_id == self._sm_public.local_peer_id
                                 or peer_id == self._sm_world.local_peer_id):
            continue
        addrs = self.get_addrs(peer_id)
        if addrs is not None:
            ret_addrs.append(addrs)
            ret_peer_ids.append(peer_id)
    if not return_peer_ids_too:
        return ret_addrs
    else:
        return ret_addrs, ret_peer_ids

Returns the address lists of the peers with exactly the role role whose addresses are known. With return_peer_ids_too=True it returns the tuple (addresses, peer_ids) in matching order. With discard_yourself=True it skips the two peer ids of this node. An unknown role gives empty lists.

count_by_role

count_by_role(role: int) -> int
Source code in unaiverse/networking/node/connpool.py
def count_by_role(self, role: int) -> int:
    """Counts the number of peers with a specific role.

    Args:
        role: The integer role to count.

    Returns:
        The number of peers with that role.
    """
    if role in self.role_to_peer_ids:
        return len(self.role_to_peer_ids[role])
    else:
        return 0

Returns the number of peers with exactly the role role.

set_world

set_world(world_peer_id: str | None) -> None
Source code in unaiverse/networking/node/connpool.py
def set_world(self, world_peer_id: str | None) -> None:
    """Sets the peer ID of the world node.

    Args:
        world_peer_id: The peer ID of the world node, or None to clear it.
    """
    self._sm_world.world_node_peer_id = world_peer_id
    if world_peer_id is None:

        # Out of the world: no roster to wait for, nothing held
        self._roster_wait_tag = None
        self._held_world_dials.clear()

Writes the world peer id of the world node that this agent belongs to. The value None clears it. It also ends the wait for the roster and discards the dials held by that wait. The world routing reads this value to put the world node in its pool. The node calls it when it joins and leaves a world. start_world_handoff calls it at the start of a join.

get_world_node_peer_id

get_world_node_peer_id() -> str | None
Source code in unaiverse/networking/node/connpool.py
def get_world_node_peer_id(self) -> str | None:
    """Returns the PRIVATE peer ID of the world node, i.e. the REMOTE world host we joined,
    as written by set_world. This is deliberately NOT our own world/private peer-id:
    that one is Node.get_world_peer_id (conn[P2P_WORLD].peer_id). The name was
    get_world_peer_id, renamed to drop the collision with Node's same-named accessor
    that means the opposite thing.

    Args:
        None.

    Returns:
        The world node's peer ID, or None before sm_world is built / when unset.
    """
    return self._sm_world.world_node_peer_id if self._sm_world is not None else None

Returns the world peer id of the world node this agent joined. Outside a world and before attach_session_policy it returns None. It never returns the peer id of this node (that one is world_peer_id).

set_world_agents_list

set_world_agents_list(world_agents_list_peer_infos: list[dict] | None) -> None
Source code in unaiverse/networking/node/connpool.py
def set_world_agents_list(self, world_agents_list_peer_infos: list[dict] | None) -> None:
    """Sets the list of all world agents based on a provided list of peer information.

    Args:
        world_agents_list_peer_infos: A list of dictionaries containing peer information for world agents.
    """

    # Clearing previous information
    to_remove = []
    for peer_id, misc in self.peer_id_to_misc.items():
        if misc & 1 == 1 and misc & 2 == 0:
            to_remove.append((peer_id, misc))

    for peer_id, misc in to_remove:
        del self.peer_id_to_misc[peer_id]
        if peer_id in self.peer_id_to_addrs:
            del self.peer_id_to_addrs[peer_id]
        self.role_to_peer_ids[misc].discard(peer_id)

    # Setting new information
    if world_agents_list_peer_infos is not None and len(world_agents_list_peer_infos) > 0:
        self._sm_world.world_agents_set = {x['id'] for x in world_agents_list_peer_infos}
        for x in world_agents_list_peer_infos:
            self.peer_id_to_addrs[x['id']] = x['addrs']
            self.set_role(x['id'], x['misc'])
    else:
        self._sm_world.world_agents_set = set()

Replaces the list of the world agents. It first deletes the role and the addresses of every peer whose role marks an agent. It then writes the new set of agents in the world manager and calls set_role for each entry of world_agents_list_peer_infos (dictionaries with id, addrs and misc) after storing its addresses. With None or an empty list the world has no agents afterwards. The rendezvous reader calls it on each new roster and the node calls it when it leaves a world.

set_world_masters_list

set_world_masters_list(world_masters_list_peer_infos: list[dict] | None) -> None
Source code in unaiverse/networking/node/connpool.py
def set_world_masters_list(self, world_masters_list_peer_infos: list[dict] | None) -> None:
    """Sets the list of all world masters based on a provided list of peer information.

    Args:
        world_masters_list_peer_infos: A list of dictionaries containing peer information for world masters.
    """

    # Clearing previous information
    to_remove = []
    for peer_id, misc in self.peer_id_to_misc.items():
        if misc & 1 == 1 and misc & 2 == 2:
            to_remove.append((peer_id, misc))

    for peer_id, misc in to_remove:
        del self.peer_id_to_misc[peer_id]
        if peer_id in self.peer_id_to_addrs:
            del self.peer_id_to_addrs[peer_id]
        self.role_to_peer_ids[misc].discard(peer_id)

    # Setting new information
    if world_masters_list_peer_infos is not None and len(world_masters_list_peer_infos) > 0:
        self._sm_world.world_masters_set = {x['id'] for x in world_masters_list_peer_infos}
        for x in world_masters_list_peer_infos:
            self.peer_id_to_addrs[x['id']] = x['addrs']
            self.set_role(x['id'], x['misc'])
    else:
        self._sm_world.world_masters_set = set()

The counterpart of set_world_agents_list for the masters (misc & 3 == 3).

add_to_world_agents_list

add_to_world_agents_list(peer_id: str, addrs: list[str], role: int = -1, provisional_ttl_s: float | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
def add_to_world_agents_list(self, peer_id: str, addrs: list[str], role: int = -1,
                             provisional_ttl_s: float | None = None) -> None:
    """Adds a new world agent to the list.

    Args:
        peer_id: The peer ID of the new agent.
        addrs: A list of addresses for the new agent.
        role: The role assigned to the agent.
        provisional_ttl_s: When set, the entry is a grant-time pre-admission
            that expires after this many seconds unless confirmed; calling
            again WITHOUT it (the world-side registration) confirms the entry.
    """
    self._sm_world.world_agents_set.add(peer_id)

    # This assumes that the WORLD MASTER/AGENT BIT is the first one
    assert role & 1 == 1, "Expecting the first bit of the role to be 1 for world agents"
    assert role & 2 == 0, "Expecting the second bit of the role to be 0 for world agents"
    self.peer_id_to_addrs[peer_id] = addrs
    self.set_role(peer_id, role)
    if provisional_ttl_s is not None:
        self.world_preadmissions[peer_id] = time.monotonic() + provisional_ttl_s
    else:
        self.world_preadmissions.pop(peer_id, None)

Adds one agent to the members of the world. A world node calls it twice for a joiner. The call at grant time passes provisional_ttl_s and makes a pre-admission that expires unless confirmed. The call on the world network without a TTL confirms it once the joiner redeems the grant. role must have bit 0 equal to 1 and bit 1 equal to 0 or AssertionError is raised. Its default of -1 never passes that check and the caller always passes a role.

add_to_world_masters_list

add_to_world_masters_list(peer_id: str, addrs: list[str], role: int = -1, provisional_ttl_s: float | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
def add_to_world_masters_list(self, peer_id: str, addrs: list[str], role: int = -1,
                              provisional_ttl_s: float | None = None) -> None:
    """Adds a new world master to the list.

    Args:
        peer_id: The peer ID of the new master.
        addrs: A list of addresses for the new master.
        role: The role assigned to the master.
        provisional_ttl_s: When set, the entry is a grant-time pre-admission
            that expires after this many seconds unless confirmed; calling
            again WITHOUT it (the world-side registration) confirms the entry.
    """
    self._sm_world.world_masters_set.add(peer_id)

    # This assumes that the WORLD MASTER/AGENT BIT is the first one
    assert role & 1 == 1, "Expecting the first bit of the role to be 1 for world masters"
    assert role & 2 == 2, "Expecting the second bit of the role to be 1 for world masters"
    self.peer_id_to_addrs[peer_id] = addrs
    self.set_role(peer_id, role)
    if provisional_ttl_s is not None:
        self.world_preadmissions[peer_id] = time.monotonic() + provisional_ttl_s
    else:
        self.world_preadmissions.pop(peer_id, None)

The counterpart of add_to_world_agents_list for a master. role must have bits 0 and 1 both equal to 1.

remove_from_world_lists

remove_from_world_lists(peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
def remove_from_world_lists(self, peer_id: str) -> None:
    """Drops a peer from the world agents/masters lists and the role/address
    bookkeeping. The world host calls this when a member's world Session
    terminates, so the routing pass and the rendezvous publish stop
    advertising it."""
    self._sm_world.world_agents_set.discard(peer_id)
    self._sm_world.world_masters_set.discard(peer_id)
    self.world_preadmissions.pop(peer_id, None)
    self.peer_id_to_addrs.pop(peer_id, None)
    misc = self.peer_id_to_misc.pop(peer_id, None)
    if misc in self.role_to_peer_ids:
        self.role_to_peer_ids[misc].discard(peer_id)
        if not self.role_to_peer_ids[misc]:
            del self.role_to_peer_ids[misc]

Removes a peer from the agents and masters of the world, from the pre-admissions, from peer_id_to_addrs, from peer_id_to_misc and from role_to_peer_ids (an emptied role set is deleted). A world node calls it when the world Session of a member ends. The next roster then no longer lists that member.

sweep_world_preadmissions

sweep_world_preadmissions(now: float | None = None) -> list[str]
Source code in unaiverse/networking/node/connpool.py
def sweep_world_preadmissions(self, now: float | None = None) -> list[str]:
    """World host: drop the pre-admitted joiners whose deadline expired without
    a world-side registration (the grant was never redeemed). The public
    carrier's own FAILED cannot clean these up — it carries the PUBLIC peer-id
    while the pre-admission is keyed on the private one — so the deadline is
    the collector. Returns the removed peer-ids (for the caller's log)."""
    if not self.world_preadmissions:
        return []
    if now is None:
        now = time.monotonic()
    expired = [pid for pid, deadline in self.world_preadmissions.items()
               if deadline <= now]
    for pid in expired:
        self.remove_from_world_lists(pid)   # pops the deadline too
    return expired

On a world node it calls remove_from_world_lists on every pre-admitted joiner whose deadline passed and returns their peer ids. now is a time.monotonic() value and the method reads the clock itself when now is None. The failure of the public carrier cannot remove these entries because its event names the public peer id while the pre-admissions are keyed by the world peer id. The node calls it at every cycle before update.

get_world_roster_peer_infos

get_world_roster_peer_infos() -> tuple[list[dict], list[dict]]
Source code in unaiverse/networking/node/connpool.py
def get_world_roster_peer_infos(self) -> tuple[list[dict], list[dict]]:
    """World host: the peer infos of the confirmed world members, the roster the
    host advertises (world summary of its profile and rendezvous publish alike).

    A pre-admitted joiner enters the world pools as soon as its transport connects,
    because the perimeter needs it there, but it is not a member until the world-side
    registration drops its pre-admission deadline. Advertising it earlier would send
    the other members to dial a peer that does not know them yet, which cuts them and
    quarantines them.

    A member whose transport to us dropped leaves the pools at once, but it stays a
    member while its world Session rides its reconnect window, and the terminal event
    of that Session unlists it. Leaving it out would make every other member cut its
    Sessions with it at the next publication.

    Every entry says what the members need of a member, the same whether it is connected
    or in its window: the addresses it registered with, which its address updates
    rewrite in place, and its role, in the order of the peer-ids. A transport that drops
    and comes back changes none of it, so it is not a change of the roster (the entry
    of the pool, rebuilt at the return, carries the addresses of the transport).

    Returns:
        A tuple with the peer infos of the world agents and of the world masters.
    """
    provisional = self.world_preadmissions
    connected = {c['id'] for c in
                 self.get_all_connected_peer_infos(NodeConn.WORLD_AGENTS | NodeConn.WORLD_MASTERS)}
    world_masters = self._sm_world.world_masters_set
    agents, masters = [], []
    for peer_id in sorted(self._sm_world.world_agents_set | world_masters):
        if peer_id in provisional or not (peer_id in connected or self._sm_world.is_in_grace(peer_id)):
            continue
        info = {'id': peer_id, 'addrs': list(self.peer_id_to_addrs.get(peer_id) or []),
                'misc': self.peer_id_to_misc.get(peer_id, 0)}
        (masters if peer_id in world_masters else agents).append(info)
    return agents, masters

On a world node it returns the roster to publish as the tuple (agents, masters). Both items are lists of {"id", "addrs", "misc"} sorted by peer id. A confirmed member (no pending pre-admission) is listed when its transport is connected or its world Session is RECONNECTING. A pre-admitted joiner is left out. The other members would otherwise dial a peer that does not know them yet and the perimeter of that peer would cut them. A member in its reconnect window stays in to keep the other members from cutting their Sessions with it. The node publishes this roster on the rendezvous and in the profile of the world.

set_world_agents_and_world_masters_lists_from_rendezvous async

set_world_agents_and_world_masters_lists_from_rendezvous() -> None
Source code in unaiverse/networking/node/connpool.py
async def set_world_agents_and_world_masters_lists_from_rendezvous(self) -> None:
    """Updates the lists of world agents and masters using data from the rendezvous topic (async)."""
    rendezvous_state = self._sm_world.rendezvous_peers()

    if rendezvous_state is not None:
        tag = rendezvous_state.get('update_count', -1)

        if tag > self.rendezvous_tag:
            self.rendezvous_tag = tag
            rendezvous_peer_infos = rendezvous_state.get('peers', [])

            world_agents_peer_infos = []
            world_masters_peer_infos = []

            log.cpool(f"Rendezvous peer infos (tag: {tag}, peers: "
                      f"{len(rendezvous_peer_infos)} peers)", sub=self._sm_world.log_sub)
            log.cpool(f"Rendezvous message included peer IDs: "
                      f"{[p['id'] for p in rendezvous_peer_infos]})", sub="prv")

            for c in rendezvous_peer_infos:
                if c['addrs'] is None:
                    log.cpool(f"Skipping a peer with None addrs (unexpected)", sub=self._sm_world.log_sub)
                    continue

                # if len(c['addrs']) == 0:
                #    log.cpool(f"Skipping a peer with zero-length addrs-list (unexpected)")
                #    continue
                if (c['misc'] & 1) == 1 and (c['misc'] & 2) == 0:
                    world_agents_peer_infos.append(c)
                elif (c['misc'] & 1) == 1 and (c['misc'] & 2) == 2:
                    world_masters_peer_infos.append(c)
                else:

                    # An unexpected 'misc' from the rendezvous must not be fatal (this runs
                    # every cycle from the main loop): log and skip the entry.
                    log.error("Unexpected value of the 'misc' field, skipping: " + str(c),
                              sub=self._sm_world.log_sub)

            # Updating lists
            self.set_world_agents_list(world_agents_peer_infos)
            self.set_world_masters_list(world_masters_peer_infos)

            # A roster newer than the grant that lists us ends the joiner's wait: the
            # members got the same publication, so they know us now
            if (self._roster_wait_tag is not None and tag > self._roster_wait_tag and
                    any(c['id'] == self._sm_world.local_peer_id for c in rendezvous_peer_infos)):
                self._roster_wait_tag = None
                log.misc(f"the world's roster lists us (tag: {tag}): the held dials go out",
                         sub=self._sm_world.log_sub)

On an agent it reads the latest roster of the rendezvous of the world from the world manager (async). A roster whose update_count is not larger than rendezvous_tag is ignored. A newer one updates the tag. Its peers are split into agents (misc & 3 == 1) and masters (misc & 3 == 3) and the entries with no addresses or an unexpected misc are skipped. The two list writers then receive the result. The wait for a roster that lists this agent (see start_world_handoff) ends when this roster is newer than the grant and lists the world peer id of this agent. The held dials then go out at the next pump. The node calls it at every cycle before update.

reset_rendezvous_tag

reset_rendezvous_tag() -> None
Source code in unaiverse/networking/node/connpool.py
def reset_rendezvous_tag(self) -> None:
    """Resets the rendezvous tag to its initial state."""
    self.rendezvous_tag = -1

Writes -1 into rendezvous_tag so that the next roster is accepted whatever its count. The node calls it when it enters or leaves a world.

remove_all_world_agents async

remove_all_world_agents() -> None
Source code in unaiverse/networking/node/connpool.py
async def remove_all_world_agents(self) -> None:
    """GOAWAY-close and drop every connected world peer (the WORLD pools: agents,
    masters and node alike) from the pools and role lists (async). The reason
    WORLD_DISENGAGEMENT closes each ex-companion's Session cleanly — the GOAWAY
    actually reaches them now that the transport falls with the deferred
    settlement cut instead of being reset under the write — so they observe
    CLOSED (no reconnect) instead of a drop that would leave them ESTABLISHED
    to re-dial and re-enrol peers of a world we just left."""
    peer_infos = self.get_all_connected_peer_infos(NodeConn.WORLD)
    for c in peer_infos:
        peer_id = c['id']
        await self.drop_peer(peer_id, WORLD_DISENGAGEMENT)
        if peer_id in self.peer_id_to_addrs:
            del self.peer_id_to_addrs[peer_id]
        for role, peer_ids in self.role_to_peer_ids.items():
            if peer_id not in peer_ids:
                continue
            if role & 1 == 1:
                peer_ids.remove(peer_id)

Closes the relation with every peer in the WORLD pools (agents, masters and world node) through drop_peer(peer_id, WORLD_DISENGAGEMENT) (async). It also removes their addresses and takes them out of every role set with bit 0. Each peer receives a GOAWAY and observes CLOSED instead of a dropped link that it would try to recover. The node calls it when this agent leaves a world.

membership_snapshot

membership_snapshot() -> WorldMembership
Source code in unaiverse/networking/node/connpool.py
def membership_snapshot(self) -> WorldMembership:
    """Freeze the current world membership into an immutable per-cycle view. The pure
    membership (the two sets + world_node_peer_id) is read from sm_world, where it now
    lives next to the Sessions it gates; inspector_peer_id is the Coordinator's own
    orthogonal exception. The sets are copied into frozensets so a snapshot
    already taken cannot change if the membership mutates later (and cannot be mutated
    by the routing itself). Before attach_session_policy builds sm_world the membership
    reads empty."""
    sm = self._sm_world
    if sm is None:
        world_agents, world_masters, world_node_peer_id = frozenset(), frozenset(), None
    else:
        world_agents = frozenset(sm.world_agents_set)
        world_masters = frozenset(sm.world_masters_set)
        world_node_peer_id = sm.world_node_peer_id
    return WorldMembership(
        world_agents=world_agents,
        world_masters=world_masters,
        world_node_peer_id=world_node_peer_id,
        inspector_peer_id=self.inspector_peer_id,
    )

Builds a WorldMembership from the current sets of the world manager and inspector_peer_id. The sets are copied into frozenset objects. Before attach_session_policy the snapshot is empty. update calls it once per cycle.

update async

update() -> tuple[dict, dict]
Source code in unaiverse/networking/node/connpool.py
async def update(self) -> tuple[dict, dict]:
    """Coordinator per-cycle update. First refresh the world SessionManager's KNOWN
    roster (and the role/addrs it carries) from the rendezvous, so the perimeter and
    facade see this cycle's roster rather than the previous one and the KNOWN sync
    stays out of the pool/diff path. Then run the transport-driven per-instance
    reconcile: one immutable membership snapshot for the whole cycle, fanned out to
    each SessionManager in registration order (public then world), merging the
    per-instance diffs. The pool_name keys are disjoint across the two instances (IN/OUT_PUBLIC vs
    IN/OUT_WORLD_*), so the merge is a plain dict.update, asserted to be sure (async)."""
    self._sync_known_world_peers()

    self.pool_name_to_added_in_last_update = {}
    self.pool_name_to_removed_in_last_update = {}
    membership = self.membership_snapshot()
    self._cycle_membership = membership  # publish this cycle's snapshot for get_messages' gate

    # The SM is the instance: iterate the managers (public then world) instead of the
    # raw P2P handles. _session_managers preserves the public-before-world order the
    # cross-pool guard relies on (a peer-id enters at most one pool, public winning).
    for sm in self._session_managers:
        added_local, removed_local = await self._reconcile_instance(sm, membership)
        assert self.pool_name_to_added_in_last_update.keys().isdisjoint(added_local.keys()), \
            "pool_name keys must be disjoint across P2P instances"
        assert self.pool_name_to_removed_in_last_update.keys().isdisjoint(removed_local.keys()), \
            "pool_name keys must be disjoint across P2P instances"
        self.pool_name_to_added_in_last_update.update(added_local)
        self.pool_name_to_removed_in_last_update.update(removed_local)

    return self.pool_name_to_added_in_last_update, self.pool_name_to_removed_in_last_update

Runs the per-cycle update of the pools (async). It returns (added, removed) as two dict[str, set[str]] that hold only the pools that changed. The node calls it at every cycle.

  1. It hands the known world peers (peer_id_to_addrs with their roles, minus this node) to SessionManager.sync_known_peers of the world manager.
  2. It builds one WorldMembership and keeps it as the snapshot of the cycle for get_messages.
  3. For each manager, public first, it reads the connected peers of the transport and asks SessionManager.reconcile to classify them into pools. On the world network this also cuts every peer outside the membership. Each pool is then compared with the result. New peers enter through add. Gone peers appear in removed and stay in their pool until the node removes them with on_peer_disconnected.

A manager whose transport cannot list its peers is skipped for that cycle. A transient failure therefore never empties the pools.

Messages

get_messages async

get_messages(p2p_name: str, allowed_not_connected_peers: set | None = None, kind: str = 'all') -> tuple[list[Msg], list[SessionInbound]]
Source code in unaiverse/networking/node/connpool.py
async def get_messages(
    self,
    p2p_name: str,
    allowed_not_connected_peers: set | None = None,
    kind: str = "all",
) -> tuple[list[Msg], list[SessionInbound]]:
    """Retrieves and verifies all messages from a specified P2P network (async).

    Returns a tuple `(chat_messages, session_messages)`:
      * `chat_messages` are decoded `Msg` objects whose `piggyback` JWT has been
        verified (the existing chat / pubsub flow, unchanged).
      * `session_messages` are raw per-stage Session payloads already split off and
        decoded upstream by P2P.get_messages (the session-protocol partition lives in
        the transport tier); the Coordinator forwards them as-is, skipping the chat Msg
        decoding and JWT verification, because identity is established cryptographically
        inside the Session handshake (sig_b / sig_a / token).

    The whole wire codec (Msg.from_bytes and the sender-mismatch check) lives in
    P2P.get_messages now (the rewrite boundary toward OP2P.js); here the Coordinator
    receives already-decoded, sender-verified Msg and does only the Node-bound
    application work: membership gate plus piggyback JWT verification.

    Args:
        p2p_name: The name of the P2P network to fetch messages from.
        allowed_not_connected_peers: must be None at the call site. The Coordinator
            admits chat from the world agents/masters of THIS CYCLE'S membership
            snapshot (the same frozen view the perimeter classifies against, not the
            live mutable set), so a mid-cycle pre-admission only enables chat at the
            next update(). Session messages are never gated on pool membership, the
            handshake itself is what enrols a peer.
        kind: "all" (default), "network" (everything but the streams, for the network
            pass) or "streams" (one message per stream channel, for the tick).
    """
    assert allowed_not_connected_peers is None, \
        "allowed_not_connected_peers is set by the Coordinator, not by the caller"
    allowed_not_connected_peers = (self._cycle_membership.world_agents
                                   | self._cycle_membership.world_masters)

    # The instance is the SM; go through its passthrough (never call P2P directly).
    # P2P has already popped the inbound batch and run the whole codec: chat frames are
    # decoded, sender-verified Msg, session frames are SessionInbound passed straight
    # through. Here we only gate membership and verify the piggyback token.
    sm = self._sm_by_name(p2p_name)
    chat_messages, session_messages = sm.get_messages(kind)
    processed_messages: list[Msg] = []

    if chat_messages or session_messages:
        self.__last_recv_time = time.time()

    for msg_obj in chat_messages:
        log.network(f"<<< RECEIVED {msg_obj.content_type} through channel {msg_obj.channel}", sub=sm.log_sub)

        # filter only valid messages to return: a sender already in a pool, or one
        # of this cycle's admitted world agents/masters (the frozen snapshot above).
        if (msg_obj.sender in self.peer_id_to_pool_name or
                msg_obj.sender in allowed_not_connected_peers):

            try:
                token_with_inspector_final_bit = msg_obj.piggyback
                token = token_with_inspector_final_bit[0:-1]
                inspector_mode = token_with_inspector_final_bit[-1]
                node_id, _ = await self.verify_token(token, msg_obj.sender)
                if node_id is not None:

                    # Replacing piggyback with the node ID and the flag telling if it is inspector
                    msg_obj.piggyback = node_id + inspector_mode
                    processed_messages.append(msg_obj)
                    if msg_obj.sender in self.peer_id_to_pool_name:
                        self.peer_id_to_token[msg_obj.sender] = token
                else:
                    log.error("Received a message missing expected info in the token payload "
                              "(discarding it)", sub=sm.log_sub)
            except Exception as e:
                log.error(f"Received a message with an invalid piggyback token! (discarding it) [{e}]",
                          sub=sm.log_sub)

    return processed_messages, session_messages

Pops the inbound messages of one network and returns (chat_messages, session_messages) (async).

Argument Type Default Meaning
p2p_name str P2P_PUBLIC or P2P_WORLD.
allowed_not_connected_peers set \| None None Must be None (any other value raises AssertionError). The method fills it with the agents and masters of the snapshot of the cycle.
kind str "all" "all", "network" (everything but the streams, for the network pass of the node) or "streams" (one message per stream channel, for the tick).

The transport has already decoded every frame and checked that the sender written inside each chat message is the peer that sent it (see P2P.get_messages). A chat Msg is kept only when its sender is in a pool or in the membership snapshot and its piggyback holds a valid token followed by one inspector bit. The piggyback of a kept message becomes <node id of the sender><inspector bit>. For a sender in a pool the token is also stored for get_last_token. The other chat messages are logged and discarded. The Session messages (SessionInbound) come back as they arrived because the handshake itself proves the identity of the peer and no pool or token gates them. Any message received updates the time read by passed_time_since_last_communication. The node calls it twice per pass with one call per network.

send async

send(peer_id: str, channel_trail: str | None, content_type: str, content: bytes | dict | str | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
async def send(self, peer_id: str, channel_trail: str | None,
               content_type: str, content: bytes | dict | str | None = None) -> bool:
    """Sends a direct message to a specific peer (async).

    Args:
        peer_id: The peer ID to send the message to.
        channel_trail: An optional string to append to the channel name.
        content_type: The type of content in the message.
        content: The message content.

    Returns:
        True if the message is sent successfully, otherwise False.
    """
    sm, outcome, _ = await self._deliver(peer_id, channel_trail, content_type, content)
    return outcome in ("queued", "written")

Sends a direct message to a peer (async). It returns True when the message was queued or written. It returns False in three cases: the send queue of the peer refused it, the send failed or no manager knows the peer.

Argument Type Default Meaning
peer_id str The receiver. The message goes on the network that holds a Session with it (public first) and otherwise on the network of its pool.
channel_trail str \| None A suffix of the channel or None.
content_type str One of the content types of Msg.
content bytes \| dict \| str \| None None The content.

The channel of the message is <own peer id>::dm:<peer id>-<content_type> with ~<channel_trail> appended for a non-empty trail. The own peer id is the one of the network of the receiver. The piggyback of the message is the token of this node followed by the inspector bit "0". Every content type except the three statistics types updates the time read by passed_time_since_last_communication. With the send queues on, the refusals of a full queue are counted and logged as at most one warning per peer every Custom.SEND_REFUSED_LOG_EVERY seconds (5). A False after a refusal says nothing about whether the peer is alive (see sends_are_queued). The hosted agent and world call it through self.node_conn and so does the node.

send_tracked async

send_tracked(peer_id: str, channel_trail: str | None, content_type: str, content: bytes | dict | str | None = None) -> SendTicket | None
Source code in unaiverse/networking/node/connpool.py
async def send_tracked(self, peer_id: str, channel_trail: str | None,
                       content_type: str, content: bytes | dict | str | None = None) -> SendTicket | None:
    """Sends a direct message as send() does, and returns a ticket that tells when it was written (async).

    Args:
        peer_id: The peer ID to send the message to.
        channel_trail: An optional string to append to the channel name.
        content_type: The type of content in the message.
        content: The message content.

    Returns:
        None when the send queue of the peer refused it (full); otherwise a SendTicket: queued until the send queue
        reports it, already written when the transport has no queue (the browser: its send returns once written),
        already dropped when the send failed.
    """
    sm, outcome, detail = await self._deliver(peer_id, channel_trail, content_type, content)
    if outcome == "refused":
        return None
    if outcome == "failed":
        return SendTicket(peer_id, None, status="dropped", reason=detail)
    if outcome == "written":
        return SendTicket(peer_id, None, status="written")
    key, seq = (sm.p2p_name, peer_id), detail
    ticket = SendTicket(peer_id, seq)

    # Its events may have been popped already, while the send was returning (written up to, or dropped)
    if seq <= self._written_upto.get(key, 0):
        ticket.resolve("written")
    else:
        for first, last, reason in self._recent_drops.get(key, []):
            if first <= seq <= last:
                ticket.resolve("dropped", reason)
    if ticket.status == "queued":
        self._tickets.setdefault(key, {})[seq] = ticket
    return ticket

Sends a direct message like send and returns a SendTicket that follows it (async). It returns None when the queue of the peer refused the message. Otherwise the ticket starts in one of three states.

  • "dropped" with the error as reason when the send failed.
  • "written" when the transport has no queues (the browser transport returns only once the message is written).
  • "queued" with its sequence number in every other case.

pop_send_events resolves a queued ticket. The events of the queue may have been popped while the send was still returning its sequence number. The method therefore first checks the highest sequence number already written and the last eight dropped ranges of that peer and resolves the ticket at once when they cover it. Nothing in the SDK calls it. It serves code that must know when a message has left.

sends_are_queued property

sends_are_queued: bool

True when the transport of at least one network has its send queues on. A False from send is then the refusal of a full queue and does not mean that the peer is gone (the Session keep-alive tells whether a peer is alive). When it is False (a native networking library older than the queues or the browser transport) a False from send is a failed write. Agent and World read it to interpret a failed send.

pop_send_events

pop_send_events() -> list[dict]
Source code in unaiverse/networking/node/connpool.py
def pop_send_events(self) -> list[dict]:
    """Pops the events of the send queues of every instance, each tagged with the name of its instance.

    See P2P.pop_send_events for the fields; an instance whose transport has no send queues (the browser, a
    library older than them) gives none.

    Returns:
        The list of the events, public instance first, oldest first within each.
    """
    events = []
    for sm in self._session_managers:
        for ev in sm.pop_send_events():
            ev["p2p_name"] = sm.p2p_name
            self._resolve_tickets(ev)
            events.append(ev)
    return events

Pops the events of the send queues of both networks and returns them as a list of dictionaries with an added p2p_name key. The public events come first and each network gives its events oldest first. P2P.pop_send_events describes the fields of each event. Each event also resolves the tickets of send_tracked that it covers ("written" up to a sequence number and "queue_dropped" over a range) and updates their progress on a "progress" event. A transport without queues gives no event. The node calls it once per network pass and reacts to each event.

request_keepalive_probe

request_keepalive_probe(peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
def request_keepalive_probe(self, peer_id: str) -> None:
    """Asks the Session of a peer for an early keep-alive PING (after a failed send).

    Args:
        peer_id: The peer.
    """
    sm = self._sm_of(peer_id)
    if sm is not None:
        sm.request_keepalive_probe(peer_id)

Asks the Session of a peer to send its next keep-alive PING at once instead of at the end of its period of 15 seconds. A dead peer is then confirmed within the 10 seconds of the PING timeout. The node calls it on a "write_failed" event of the send queue.

stop_sending async

stop_sending(peer_id: str, seq: int) -> bool
Source code in unaiverse/networking/node/connpool.py
async def stop_sending(self, peer_id: str, seq: int) -> bool:
    """Asks a peer to stop sending a large message that this node no longer wants (async).

    For the receiver's Stop (the browser chat): its transport already threw away what came; this tells the sender,
    through the Session of the peer (STOP_SENDING), so that the rest of the message does not travel at all. A peer
    whose HELLO did not say CAP_STOP_SENDING is not asked (it would not understand): it goes on sending, as before.

    Args:
        peer_id: The peer that sends the message.
        seq: The sequence number of the message, as its chunk frames gave it.

    Returns:
        True when the request was sent.
    """
    sm = self._sm_of(peer_id)
    sess = sm.get_session(peer_id) if sm is not None else None
    if sess is None:
        return False
    return await sess.send_stop_sending(seq)

Asks the peer that is sending a large message to stop it because this node no longer wants it (async). seq is the sequence number of the message in the queue of the sender as its chunk frames carry it. The request goes as STOP_SENDING through the Session of the peer (see Session.send_stop_sending). It returns True when the request was sent. It returns False in four cases: the peer has no Session, the Session is not ESTABLISHED, seq is not positive or the peer did not announce that it understands STOP_SENDING. A peer of the last kind keeps sending. The Python SDK never calls this method. The stop control of the chat in the browser runtime uses it.

passed_time_since_last_communication

passed_time_since_last_communication() -> float
Source code in unaiverse/networking/node/connpool.py
def passed_time_since_last_communication(self) -> float:
    """Gets the time passed since the last message sent or received on any instance.

    Returns:
        The seconds since the last communication (never negative).
    """
    passed = time.time() - max(self.__last_sent_time, self.__last_recv_time)
    return 0. if passed < 0. else passed

Returns the seconds since the last message sent (statistics excluded) or received on any network. The result is never negative. The node reads it to slow its clock down when it is idle.

subscribe async

subscribe(peer_id: str, channel: str, default_p2p_name: str | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
async def subscribe(self, peer_id: str, channel: str, default_p2p_name: str | None = None) -> bool:
    """Subscribes to a topic/channel on a P2P network (async).

    Args:
        peer_id: The peer ID associated with the topic/channel.
        channel: The name of the channel to subscribe to.
        default_p2p_name: The P2P network to fall back on when the peer's network is
            unknown; defaults to the world network when not given.

    Returns:
        True if the subscription is successful, otherwise False.
    """
    if default_p2p_name is None:
        default_p2p_name = NodeConn.P2P_WORLD

    # Resolve the owning instance's manager and subscribe through it.
    sm = self._sm_for_topic(peer_id, default_p2p_name)
    if sm is None:
        return False
    try:
        sm.subscribe_to_topic(channel)
    except (P2PError, ValueError):
        return False
    return True

Subscribes this node to a broadcast channel (async). The chosen network is the one whose own peer id is peer_id (a channel of this node). Otherwise the method uses the network of the peer and falls back to default_p2p_name (the world network when None). It returns False when no network fits or the transport refused and True otherwise. The hosted entity calls it to follow the channels of a peer.

unsubscribe async

unsubscribe(peer_id: str, channel: str, default_p2p_name: str | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
async def unsubscribe(self, peer_id: str, channel: str, default_p2p_name: str | None = None) -> bool:
    """Unsubscribes from a topic/channel on a P2P network (async).

    Args:
        peer_id: The peer ID associated with the topic/channel.
        channel: The name of the channel to unsubscribe from.
        default_p2p_name: An optional P2P network name to use if the peer's network is unknown.

    Returns:
        True if the unsubscription is successful, otherwise False.
    """

    if default_p2p_name is None:
        default_p2p_name = NodeConn.P2P_WORLD

    # Resolve the owning instance's manager and unsubscribe through it.
    sm = self._sm_for_topic(peer_id, default_p2p_name)
    if sm is None:
        return False
    try:
        sm.unsubscribe_from_topic(channel)
    except (P2PError, ValueError):
        return False
    return True

The reverse of subscribe with the same choice of network and the same return value.

publish async

publish(peer_id: str, channel: str, content_type: str, content: bytes | dict | tuple | None = None) -> bool
Source code in unaiverse/networking/node/connpool.py
async def publish(self, peer_id: str, channel: str,
                  content_type: str, content: bytes | dict | tuple | None = None) -> bool:
    """Publishes a message to a topic/channel on a P2P network (async).

    Args:
        peer_id: The peer ID associated with the topic/channel.
        channel: The name of the channel to publish to.
        content_type: The type of content in the message.
        content: The message content.

    Returns:
        True if the message is published successfully, otherwise False.
    """

    # Resolve the owning instance's manager (our own topic or the peer's instance).
    sm = self._sm_for_topic(peer_id)
    if sm is None:
        return False

    log.network(f">>> PUBLISHING {content_type} to {channel}", sub=sm.log_sub)

    # Adding sender info here
    msg = Msg(sender=sm.local_peer_id,
              content_type=content_type,
              content=content,
              channel=channel,
              piggyback=self.__token + "0")  # Adding inspector-mode bit (dummy bit here)

    # Hand the Msg object to the SM; the codec and the thread offload live in P2P.
    try:
        await sm.broadcast(channel, msg)

        # If the line above executes without raising an error, it was successful.
        return True
    except P2PError:

        # If broadcast_message fails, it will raise a P2PError. We catch it here.
        return False

Broadcasts a message on a channel of this node (async). The network is chosen as in subscribe but without a default. The message carries the token and the inspector bit as in send. It returns True when the transport accepted the message and False otherwise. Broadcast messages travel in one frame of at most 50 MB (see Large messages and files). The hosted entity calls it for its broadcast streams and the world node calls it for the roster.

reserve async

reserve(peer_id: str, p2p_name: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
async def reserve(self, peer_id: str, p2p_name: str) -> str | None:
    """Attempts to reserve a slot on a specified relay node via a P2P network (async).

    Args:
        peer_id: The peer ID of the relay node.
        p2p_name: The name of the P2P network to use.

    Returns:
        The UTC expiration timestamp of the reservation, or None if it fails.
    """
    sm = self._sm_by_name(p2p_name)
    if sm is None:
        return None
    try:
        return await sm.reserve(peer_id)
    except P2PError as e:

        # The browser has no other line that says why: its transport raises this.
        log.error(f"No relay slot on ...{peer_id[-5:]} ({p2p_name}): {e}")
        return None

Reserves a relay slot on the relay peer_id of the network p2p_name (async). It returns the expiry of the reservation as an ISO 8601 string. An unknown network or a refusal of the relay gives None and the error is logged. The node calls it to stay reachable from behind a router (see Relays).

set_turn_credentials

set_turn_credentials(ice_turn_servers: list) -> None
Source code in unaiverse/networking/node/connpool.py
def set_turn_credentials(self, ice_turn_servers: list) -> None:
    """Push TURN credentials to BOTH instances, fanning out through the SMs
    (Node -> NodeConn -> SM -> P2P). The raw transport handles stay custody-only
    behind the managers, so Node sets credentials once and both instances update."""
    self._sm_public.set_turn_credentials(ice_turn_servers)
    self._sm_world.set_turn_credentials(ice_turn_servers)

Hands both networks new credentials of the servers that the browser transport uses to traverse routers. ice_turn_servers is a list of dictionaries with keys urls, username and credential. Connections already open keep their configuration. The node calls it when it receives fresh credentials from the UNaIVERSE server.

Sessions

attach_session_policy

attach_session_policy(p2p_u: P2P, p2p_w: P2P, local_profile_factory: Callable[[], dict], decision_hook: Callable | None, token_factory: Callable[[], str] | None = None, address_lookup: Callable | None = None) -> None
Source code in unaiverse/networking/node/connpool.py
def attach_session_policy(self, p2p_u: P2P, p2p_w: P2P,
                          local_profile_factory: Callable[[], dict], decision_hook: Callable | None,
                          token_factory: Callable[[], str] | None = None,
                          address_lookup: Callable | None = None) -> None:
    """Take the two transport handles and build the two per-instance SessionManagers,
    now that both the transports and the Node policy born late are available (the profile
    factory samples self.profile, the decision hook reads world/agent/allow-list state).
    This is the single point where the Coordinator becomes operational: each manager is
    built around its P2P and owns it. The Coordinator keeps no separate transport handle,
    it reaches each instance (and its identity) through the owning manager.

    address_lookup (async node_id -> addresses, from the Node layer) goes to the public
    manager only: the root server holds the addresses of the public instance, and on
    the world instance the rendezvous keeps them current."""

    # Per-instance perimeter routing injected into each manager: the public one
    # routes by direction (no membership, never cuts); the world one classifies
    # against the snapshot and cuts unclassifiable peers on its P2P instance.
    self._sm_public = SessionManager(
        p2p=p2p_u,
        p2p_name=NodeConn.P2P_PUBLIC,
        local_peer_id=p2p_u.peer_id,
        local_node_id=self._local_node_id,
        local_profile_factory=local_profile_factory,
        decision_hook=decision_hook,
        token_verifier=self.verify_token_claims,
        token_factory=token_factory,
        routing_classifier=NodeConn._route_public,
        address_lookup=address_lookup,
    )
    self._sm_world = SessionManager(
        p2p=p2p_w,
        p2p_name=NodeConn.P2P_WORLD,
        local_peer_id=p2p_w.peer_id,
        local_node_id=self._local_node_id,
        local_profile_factory=local_profile_factory,
        decision_hook=decision_hook,
        token_verifier=self.verify_token_claims,
        token_factory=token_factory,
        routing_classifier=NodeConn._route_world,
    )
    self.set_session_managers(self._sm_public, self._sm_world)

Makes the object operational. It receives the transports of the public network (p2p_u) and of the world network (p2p_w) and builds one SessionManager around each. Both managers receive four objects.

  • local_profile_factory, a callable that returns the current profile of the node as a JSON-serializable dictionary.
  • decision_hook, the policy that accepts or refuses an offer (see Session).
  • token_factory, a callable that returns the current token of this node.
  • verify_token_claims as their token verifier.

The public manager also receives address_lookup, an async callable from a node id to its addresses on the UNaIVERSE server. The server holds only the public addresses and the rendezvous keeps the world addresses current. The public manager routes peers by direction only. The world manager also checks them against the membership. The node calls it once after it has created both transports.

set_session_managers

set_session_managers(*session_managers: SessionManager) -> None
Source code in unaiverse/networking/node/connpool.py
def set_session_managers(self, *session_managers: SessionManager) -> None:
    """Register the per-instance SessionManagers so conn can answer per-peer
    Session-state queries on behalf of the hosted entity. Called by
    attach_session_policy (and directly by unit tests with stub managers).

    This is also where the SM (the instance) is wired into the per-instance index and
    into each pool triple's instance slot, now that the managers exist: __init__ seeded
    the triples with None and recorded each pool's p2p_name. Unit tests that build a
    bare NodeConn via __new__ (no _init_pools) have no triples to wire, hence the
    guard."""
    self._session_managers = [sm for sm in session_managers if sm is not None]
    self._p2p_name_to_sm = {sm.p2p_name: sm for sm in self._session_managers
                           if getattr(sm, "p2p_name", None) is not None}
    triples = getattr(self, "pool_name_to_pool_triple", None)
    if triples:
        for pool_name, triple in triples.items():
            triple[2] = self._p2p_name_to_sm.get(self._pool_name_to_p2p_name[pool_name])

Registers the managers and binds each pool to the manager of its network. It also fills the index that finds a manager by network name. attach_session_policy calls it and unit tests call it with stub managers. None entries are ignored.

pump_sessions async

pump_sessions(inbound_by_p2p_name: dict, now: float) -> list
Source code in unaiverse/networking/node/connpool.py
async def pump_sessions(self, inbound_by_p2p_name: dict, now: float) -> list:
    """Per-cycle Session pump, owned by the Coordinator: deliver every inbound
    Session message to its instance's manager, then tick every manager, returning a
    FLAT list of SessionEvent in generation order (all delivers, public before world,
    then all ticks, same order). Node keeps the single dispatch site
    (_dispatch_session_event), so this only moves the per-instance iteration off Node (async).

    Mirrors the legacy order exactly: every deliver fires before any tick, and the
    managers are swept in registration order (public then world). The SessionInbound
    items are keyed by p2p_name; a manager with no inbound this cycle still ticks."""
    events: list = []

    # Deliver pass (public then world), every inbound of each instance in order.
    for sm in self._session_managers:
        for inb in inbound_by_p2p_name.get(sm.p2p_name, []):
            events.extend(await sm.deliver(inb.peer_id, inb.protocol_id, inb.sess_msg))

    # Tick pass (same order): timeouts + keep-alive PING/PONG.
    for sm in self._session_managers:
        events.extend(await sm.tick(now))
    events.extend(await self._release_held_world_dials())

    self._tell_transports_about_peers(events)
    return events

Runs one Session pump and returns the events in the order of their production (async). inbound_by_p2p_name maps P2P_PUBLIC and P2P_WORLD to the SessionInbound lists returned by get_messages. now is a time.monotonic() value.

  1. Every inbound message of the public network goes to SessionManager.deliver before every one of the world network.
  2. SessionManager.tick runs on the public manager and then on the world manager.
  3. The world dials held by the wait for the roster go out when that wait is over (see start_world_handoff).
  4. For every ESTABLISHED and RESUMED event the method tells the transport of its network what the peer can receive. It passes the capability bits of the HELLO of the peer and the max_message_size and max_file_size of the dynamic part of its profile.

A manager with no inbound message still ticks. The node calls it once per network pass and dispatches the events it returns.

on_peer_disconnected async

on_peer_disconnected(peer_id: str) -> list
Source code in unaiverse/networking/node/connpool.py
async def on_peer_disconnected(self, peer_id: str) -> list:
    """React to a transport disconnect: fan it to every instance's manager
    (ESTABLISHED -> RECONNECTING grace, in-handshake states -> FAILED) and sync the
    pool bookkeeping (``_evict_from_pools``), returning the flat list of resulting
    SessionEvent (public before world) for Node to dispatch (async).

    The link is already gone, so this evicts the pool WITHOUT a transport disconnect
    (unlike the voluntary ``drop_peer``). This is the involuntary pool-sync: it runs in
    BOTH the grace case (the RECONNECTING Session survives, the pool self-heals on the
    next update() if the peer RESUMEs) and the terminal case, so Node never issues a
    bare pool-remove itself."""
    events: list = []
    for sm in self._session_managers:
        events.extend(await sm.on_peer_disconnected(peer_id))
    self._evict_from_pools(peer_id)
    return events

Tells both managers that the transport lost a peer and returns their events with the public ones first (async). An ESTABLISHED Session moves to RECONNECTING. A Session in the middle of its handshake fails (see SessionManager.on_peer_disconnected). The peer then leaves its pool without a disconnect because the link is already gone. The node calls it for each peer that update reports as removed.

on_peer_reconnected async

on_peer_reconnected(peer_id: str) -> list
Source code in unaiverse/networking/node/connpool.py
async def on_peer_reconnected(self, peer_id: str) -> list:
    """Fan a transport reconnect to every instance's manager and return the flat list
    of resulting SessionEvent (public before world). A no-op unless a Session for the
    peer is RECONNECTING (mid-grace), so feeding fresh first-time connections is safe (async)."""
    events: list = []
    for sm in self._session_managers:
        events.extend(await sm.on_peer_reconnected(peer_id))
    return events

Tells both managers that the transport sees a peer again and returns their events (async). Only a RECONNECTING Session reacts. An initiator sends RESUME and a responder sends a probe. A call for a peer seen for the first time is harmless. The node calls it for each peer that update reports as added.

is_in_grace

is_in_grace(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_in_grace(self, peer_id: str) -> bool:
    """True if any instance holds a Session for this peer riding its reconnect grace
    (RECONNECTING). The Node uses this to keep the enrolment alive across a transport
    blip (pool-remove) instead of a full purge, without reaching into Session state."""
    return any(sm.is_in_grace(peer_id) for sm in self._session_managers)

Returns True when a Session of the peer is RECONNECTING on either network. The node then keeps the peer among its known agents across the drop of the link instead of purging it at once.

is_peer_session_pending

is_peer_session_pending(peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_peer_session_pending(self, peer_id: str) -> bool:
    """True if `peer_id` has a Session whose *first* handshake is still in
    flight (it exists but has never reached ESTABLISHED) on any registered
    instance. This is the session-era replacement for the old "connected but
    not yet managed" notion behind Agent.agents_are_waiting.

    RECONNECTING is deliberately excluded: such a peer was already established
    (already managed) and is merely re-establishing, so it is not "waiting to
    be managed". KNOWN is excluded too: it is a peer known from the rendezvous
    whose initiator has not dialed yet, so no handshake is in flight. Returns
    False for no Session / KNOWN / ESTABLISHED / RECONNECTING / terminal
    (FAILED, CLOSED).

    The per-state classification lives in SessionManager.is_handshake_in_flight
    (next to SessionState); the Coordinator only aggregates across its instances, so
    connpool no longer imports the session enum."""
    return any(sm.is_handshake_in_flight(peer_id) for sm in self._session_managers)

Returns True when the peer has a Session on either network whose first handshake is in flight. Such a Session has never reached ESTABLISHED and is neither KNOWN nor RECONNECTING nor terminal. Agent.agents_are_waiting uses it.

requires_fast_clock

requires_fast_clock() -> bool
Source code in unaiverse/networking/node/connpool.py
def requires_fast_clock(self) -> bool:
    """True if any registered SessionManager has a Session that needs the main loop
    at full speed (see SessionManager.requires_fast_clock). The Coordinator aggregates
    across its instances so the Node's clock-pacing decision is one state-based query
    instead of reaching into each manager. This supersedes the old idle check that
    counted only ESTABLISHED/RECONNECTING and so let a slowed clock starve handshakes
    in flight."""
    return any(sm.requires_fast_clock() for sm in self._session_managers)

Returns True when a Session on either network is in any state other than KNOWN, FAILED and CLOSED. The node then keeps its main loop at full speed because the timers of the handshake, of the keep-alive and of the closing assume a responsive loop.

initiate_session async

initiate_session(p2p_name: str, peer_id: str, addresses: list, is_world_join: bool = False, remote_node_id_hint: str | None = None, reject_relay: bool = False) -> list
Source code in unaiverse/networking/node/connpool.py
async def initiate_session(self, p2p_name: str, peer_id: str, addresses: list,
                           is_world_join: bool = False, remote_node_id_hint: str | None = None,
                           reject_relay: bool = False) -> list:
    """Open an initiator Session to `peer_id` on the named instance and return the
    start-up events for Node to dispatch (and to read a terminal FAILED from). The
    grant-carrying world initiate stays on the handoff path (start_world_handoff) (async).

    A world-join dial to a peer that already holds an ESTABLISHED world-join carrier
    with NO pending handoff is a SPENT carrier (a previous join's handoff failed and was
    rolled back): the plain intent match in initiate() would no-op and the join would
    never restart. The pending-handoff correlation lives here on the Coordinator, so we
    detect it here and tell the SM to replace the stale carrier. An in-flight handoff
    stays in _pending_world_handoff, so a live join is protected (no-op), not torn down."""
    sm = self._sm_by_name(p2p_name)
    replace_stale = (is_world_join and peer_id not in self._pending_world_handoff
                     and sm.has_established_world_join_carrier(peer_id))
    hold = (self._roster_wait_tag is not None and sm is self._sm_world and
            peer_id != self._sm_world.world_node_peer_id)
    events = await sm.initiate(
        peer_id=peer_id, addresses=addresses, is_world_join=is_world_join,
        remote_node_id_hint=remote_node_id_hint, reject_relay=reject_relay,
        replace_stale=replace_stale, hold=hold)
    sess = sm.get_session(peer_id) if hold else None
    if sess is not None and sess.state == SessionState.KNOWN and peer_id not in self._held_world_dials:
        self._held_world_dials.add(peer_id)
        log.misc(f"dial to ...{peer_id[-5:]} held until the world's roster lists us",
                 sub=self._sm_world.log_sub)
    return events

Opens an initiator Session to a peer on the network p2p_name and returns its first events (async). They may include a FAILED event for a quarantined peer. addresses are the addresses of the peer. is_world_join=True marks the public Session that asks a world for a grant. remote_node_id_hint is the node id expected at the peer. reject_relay=True fails a dial that only reaches the peer through a relay. Two checks come before the call to SessionManager.initiate.

  • A world join toward a peer that holds an ESTABLISHED carrier with no join in flight replaces that carrier. Such a carrier is a leftover of a failed join and its reuse would keep the new join from starting.
  • While this agent waits for a roster that lists it, a dial toward a member of the world other than the world node is registered and held in KNOWN. pump_sessions starts it when the wait is over.

The node calls it whenever it gets in touch with a peer.

start_world_handoff async

start_world_handoff(public_peer_id: str, world_peer_id: str, world_addrs: list, grant_blob: dict, reject_relay: bool) -> list
Source code in unaiverse/networking/node/connpool.py
async def start_world_handoff(self, public_peer_id: str, world_peer_id: str,
                              world_addrs: list, grant_blob: dict, reject_relay: bool) -> list:
    """Joiner side: record the public<->world correlation, point pool routing at the
    world host (set_world), and open the world Session to redeem the grant. Returns
    the initiate events for Node to dispatch. The redeemer's dial is a single
    attempt bounded by the grant window (see _WORLD_DIAL_*_BUDGET_S): time.time()
    matches the wall-clock the host minted expiry_unix_ms with (async)."""
    try:
        self.set_world(world_peer_id)
    except Exception:
        pass
    self._roster_wait_tag = int(grant_blob.get("rendezvous_tag", 0))
    self._roster_wait_until = time.monotonic() + _ROSTER_WAIT_MAX_S
    self._handoff.start(public_peer_id, world_peer_id)

    # The grant proves that the host is up and admits us: the world peer it names, when the host's verified token
    # attests it, is let through the ban its last relation or a cut of our perimeter left, and only that peer
    if world_peer_id in self._sm_public.attested_peers(public_peer_id):
        if self._sm_world.lift_quarantine(world_peer_id):
            log.misc(f"quarantine of ...{world_peer_id[-5:]} lifted by the grant of its host",
                     sub=self._sm_world.log_sub)
    else:
        log.misc(f"the grant names ...{world_peer_id[-5:]}, which the host's token does not attest: "
                 f"its quarantine, if any, stays", sub=self._sm_world.log_sub)
    remaining_s = int(grant_blob.get("expiry_unix_ms", 0)) / 1000.0 - time.time()
    budget_s = max(_WORLD_DIAL_MIN_BUDGET_S, min(remaining_s, _WORLD_DIAL_MAX_BUDGET_S))
    return await self._sm_world.initiate(
        world_peer_id, world_addrs, grant=grant_blob, reject_relay=reject_relay,
        dial_attempts=1, dial_budget_s=budget_s)

Starts the redemption of a grant on the world network and returns the events of the new world Session (async).

Argument Type Meaning
public_peer_id str The world node on the public network. Its Session carries the grant.
world_peer_id str The world node on the world network as named in the grant.
world_addrs list Its addresses.
grant_blob dict The grant as delivered by the ESTABLISHED event of the carrier. Its keys include rendezvous_tag and expiry_unix_ms.
reject_relay bool True to refuse a world node reached only through a relay.
  1. It points the world routing to world_peer_id (set_world).
  2. It opens the wait for a roster that lists this agent and is newer than grant_blob["rendezvous_tag"]. The wait lasts at most 30 seconds. During it the dials toward the other members are held because a member that has not read such a roster would cut this agent as an unknown peer.
  3. It records the pair in the HandoffCorrelation.
  4. It lifts the quarantine of world_peer_id on the world network only when the verified token of the carrier lists world_peer_id among the peer ids of the world node. The grant proves that the world is up and admits this agent. A world peer id missing from the token keeps its quarantine.
  5. It opens the world Session carrying the grant with one dial attempt. The budget of the dial equals the time left before the grant expires and is clamped between 15 and 35 seconds.

The node calls it when the public carrier reaches ESTABLISHED with a grant.

rollback_handoff async

rollback_handoff(peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
async def rollback_handoff(self, peer_id: str) -> None:
    """Roll back any in-flight handoff correlation for a terminal Session,
    whichever side died. The mechanics (established-skip, abort of the in-flight
    redemption, routing un-point) live in HandoffCorrelation.rollback, shared
    with the test harness (async)."""
    await self._handoff.rollback(peer_id)

Calls HandoffCorrelation.rollback (async). The node calls it on every terminal event of a Session that may be part of a join.

is_pending_handoff

is_pending_handoff(world_peer_id: str) -> bool
Source code in unaiverse/networking/node/connpool.py
def is_pending_handoff(self, world_peer_id: str) -> bool:
    """True if this world peer-id is the world side of an in-flight handoff (its world
    Session was opened by start_world_handoff), as opposed to a plain in-world
    agent-to-agent connection that carries no grant correlation."""
    return self._handoff.is_pending(world_peer_id)

Calls HandoffCorrelation.is_pending.

handoff_carrier_of

handoff_carrier_of(world_peer_id: str) -> str | None
Source code in unaiverse/networking/node/connpool.py
def handoff_carrier_of(self, world_peer_id: str) -> "str | None":
    """The public peer whose grant opened the in-flight handoff to this world peer-id
    (its carrier), or None when there is none. Node matches it against the join in
    progress before running the join body."""
    return self._handoff.carrier_of(world_peer_id)

Calls HandoffCorrelation.carrier_of.

complete_world_handoff async

complete_world_handoff(world_peer_id: str) -> None
Source code in unaiverse/networking/node/connpool.py
async def complete_world_handoff(self, world_peer_id: str) -> None:
    """The world Session established: retire the correlated public carrier — GOAWAY
    it (WORLD_HANDOFF_COMPLETE) on its still-live transport, evict it from the pools,
    and drop the correlation. No-op if this world peer-id was not part of a handoff.
    The transport itself falls with the settlement cut once the CLOSED lands (ACK or
    the CLOSING timeout); the dispatch early-returns on WORLD_HANDOFF_COMPLETE, so
    the pool eviction must happen here, not in a purge (async)."""
    public_peer_id = self._handoff.complete(world_peer_id)
    if public_peer_id is None:
        return
    if self._roster_wait_tag is not None:
        self._roster_wait_until = min(self._roster_wait_until, time.monotonic() + _ROSTER_WAIT_S)
    await self._sm_public.close_session(public_peer_id, WORLD_HANDOFF_COMPLETE)
    self._evict_from_pools(public_peer_id)

Retires the carrier of a join whose world Session is established (async). It removes the pair from the ledger and cuts the remaining wait for the roster to at most 5 seconds. It then sends a GOAWAY with WORLD_HANDOFF_COMPLETE on the public Session of the carrier and removes the carrier from the pools. The connection of the carrier is cut once its CLOSED event arrives. For a world peer id that was not part of a join the call does nothing. The node calls it when the world Session reaches ESTABLISHED.

Shutdown

The node shuts its networking down in three steps: close_all_sessions, then drain_teardown, then close_transports.

close_all_sessions async

close_all_sessions() -> None
Source code in unaiverse/networking/node/connpool.py
async def close_all_sessions(self) -> None:
    """Shutdown path: GOAWAY every Session on every instance so peers see a clean CLOSED
    instead of a liveness timeout. Events are intentionally dropped (the node is going
    down); close_all skips Sessions already CLOSING/terminal and silently aborts the
    in-flight handshakes (no farewell owed there, and the drain must be able to end) (async)."""
    for sm in self._session_managers:
        await sm.close_all()

Calls SessionManager.close_all on both managers (async). The live Sessions send a GOAWAY and the handshakes in flight are aborted. The events are discarded.

drain_teardown async

drain_teardown(budget_s: float = 3.0) -> None
Source code in unaiverse/networking/node/connpool.py
async def drain_teardown(self, budget_s: float = 3.0) -> None:
    """Shutdown drain: keep pumping ONLY the session traffic until every farewell
    settled — no Session left CLOSING (its GOAWAY_ACK arrived, or the timeout
    finalized it) and no settlement cut still pending (the transports of ended
    Sessions actually severed) — or the budget expires. Events are discarded: the
    node is going down, there is no application state left worth dispatching to.
    World instance first: a host's hosted GOAWAYs ride the world instance (async).

    This is what makes the shutdown GOAWAYs real on a network with latency: the
    send returning only means 'queued in the local muxer', and exiting (or closing
    the Go hosts) right after would destroy the queued frames. The GOAWAY_ACK
    round-trip is the end-to-end proof of delivery; the budget bounds the wait
    when a peer is gone and the 10s CLOSING timeout exceeds the shutdown patience.
    """
    deadline = time.monotonic() + budget_s
    managers = [sm for sm in reversed(self._session_managers)]
    while time.monotonic() < deadline:
        for sm in managers:
            try:
                _, session_inbounds = sm.get_messages()
                for inb in session_inbounds:
                    await sm.deliver(inb.peer_id, inb.protocol_id, inb.sess_msg)
                await sm.tick()
            except Exception as e:
                log.error(f"drain_teardown: pump on {sm.p2p_name} failed: {e}")
        if not any(sm.has_pending_teardown() for sm in managers):
            return
        await asyncio.sleep(0.05)

Keeps pumping only the Session traffic until no Session is CLOSING and no connection cut is pending or until budget_s seconds (3.0 by default) have passed (async). The world network goes first in every pass and a pause of 50 ms separates two passes. The return of a send only means that the frame is queued locally. Closing the transports right after close_all_sessions would therefore destroy the GOAWAY frames. Only the GOAWAY_ACK of each peer proves that its GOAWAY arrived. The chat messages popped during the drain are discarded. An error in a pass is logged and the drain continues.

close_transports

close_transports() -> None
Source code in unaiverse/networking/node/connpool.py
def close_transports(self) -> None:
    """Shutdown: close the Go host of every instance (world first), freeing its
    slot — until now nothing ever called P2P.close, so embedding several Nodes in
    one process leaked slots. Only the shutdown path calls this, after
    drain_teardown has let the farewells settle."""
    for sm in reversed(self._session_managers):
        try:
            sm.close_transport()
        except Exception as e:
            log.error(f"close_transports: closing {sm.p2p_name} failed: {e}")

Closes the transport of each network (world first) and frees its slot in the native networking library. Every remaining connection is cut abortively. An error is logged and the next transport is still closed.