A node keeps one Session with each peer it talks to on each of its two networks (see Sessions). A Session is a state machine that knows only its own peer. Five decisions need a view over all the peers of a network. SessionManager takes them for the network it manages:
which Session receives an inbound frame
what to answer to a peer that has no Session
which of two nodes that dial each other at the same moment keeps its dial
when a peer may be dialed again after a failure
when the connection of an ended relation is cut
A node has two managers (one for the public network and one for the world network) and its NodeConn builds both in attach_session_policy.
The manager also owns the P2P transport of its network. NodeConn reaches the transport only through the manager and the manager offers a passthrough for every transport operation that the node needs (send, broadcast, subscribe, relay reservation, peer lists).
Every method here is called by NodeConn or by the shutdown path of the node. A developer never calls them. The page describes them because they decide when a peer appears, disappears, gets refused or gets dialed again.
Each cycle of the node uses the manager in a fixed order.
NodeConn.update calls sync_known_peers (world network only) and then reconcile to classify the connected peers into pools and to cut the intruders of the world.
NodeConn.pump_sessions hands every inbound Session frame to deliver and then calls tick. That method fires the timeouts, collects the finished dials, sends the keep-alive PINGs and executes the pending connection cuts.
The node dispatches the returned SessionEvent objects.
A KNOWN Session is an initiator that the manager has registered for a peer without dialing it yet. The rendezvous of the world creates a KNOWN Session for every advertised member. A KNOWN Session costs nothing per cycle.
The quarantine of a peer is a time window after a LOST or a FAILED during which the manager refuses to dial that peer (see Quarantine).
A settlement cut is the disconnect of the connection of a peer that the manager schedules after a Session of that peer ended. A disconnect resets every stream and destroys the frames still in flight. The cut therefore waits a short linger to let the last farewell frame (a GOAWAY_ACK or a refusal) reach the peer.
The coercive cut removes a peer from the world network at once without farewell or linger.
def__init__(self,p2p:"P2P",p2p_name:str,local_peer_id:str,local_node_id:str,local_profile_factory:Callable[[],dict],decision_hook:DecisionHook|None=None,token_verifier:Callable|None=None,token_factory:Callable[[],str]|None=None,routing_classifier:Callable[[dict,Any],str|None]|None=None,address_lookup:Callable|None=None,)->None:"""Initializes the Session registry and dispatcher of one p2p instance. Args: p2p: the P2P instance this manager owns and injects into each Session (or a JS OP2P mirror in Pyodide). The manager no longer reaches the transport through the conn layer, it speaks to its P2P directly. p2p_name: the label of the P2P instance this manager owns (e.g. "p2p_public"), used for SessionEvent tagging. local_peer_id: our libp2p peer-id on `p2p_name` (used for tie-breaker). local_node_id: our application node-id (passed into each Session). local_profile_factory: () -> NodeProfile dict snapshot (JSON-serializable). decision_hook: responder side — async callback to accept/reject an inbound PROFILE_OFFER and (for a world host) produce the WorldGrant spec. None ⇒ Sessions accept by default (v1 agent happy-path). token_verifier: async callable (token, p2p_peer) -> (node_id, cv_hash, p2p_peers, exp, code_hash), forwarded into every Session; None ⇒ no token check (v1 path). token_factory: () -> our current node token, forwarded into every Session; None ⇒ no token sent. routing_classifier: pure classifier (peer_info, membership) -> pool_name | None, injected by the Coordinator (which owns the pool taxonomy); None ⇒ no pool classification. address_lookup: initiator side — async node_id -> addresses of that node, handed to every initiator Session (see Session); None ⇒ no lookup. """self.p2p=p2pself.p2p_name=p2p_nameself.local_peer_id=local_peer_idself.local_node_id=local_node_idself._local_profile_factory=local_profile_factoryself._decision_hook=decision_hook# Token capabilities (RT plumbing), forwarded into every Session this manager# builds. token_verifier(token, p2p_peer) -> (node_id, cv_hash, p2p_peers, exp,# code_hash); token_factory() -> our current node token (re-sampled per# handshake so periodic refresh shows).self._token_verifier=token_verifierself._token_factory=token_factoryself._address_lookup=address_lookup# Last node token broadcast to peers; tick() pushes a TOKEN_UPDATE when# token_factory() (i.e. self.node_token) changes. Seed with the current value# so the initial token is not re-broadcast.self._last_pushed_token=token_factory()iftoken_factoryisnotNoneelseNone# Per-instance perimeter routing, injected by the Coordinator (which owns the# pool taxonomy): a pure classifier (peer_info, membership) -> pool_name | None.# The unclassifiable-world-peer cut is no longer an injected callable: the manager# owns its P2P, so it drops the peer itself (self.drop), keeping the# Node -> NodeConn -> SM -> P2P chain intact.self._routing_classifier=routing_classifierself._label=_p2p_label(p2p_name)# peer_id → Session (at most one Session per peer in this p2p instance).# Two views: `_sessions` is the full registry (including inert KNOWN# Sessions for known-but-not-dialed peers); `_active_sessions` mirrors only# the ones the per-cycle tick must sweep (anything past KNOWN), so a large# roster of KNOWN peers costs O(1) per cycle instead of O(N).self._sessions:dict[str,Session]={}self._active_sessions:dict[str,Session]={}# peer_id → monotonic timestamp until which dials are refused.self._quarantine:dict[str,float]={}# peer_id → monotonic deadline of a deferred transport cut (the settlement# cut), scheduled by _on_terminal when a Session ends, or after a reply sent# on behalf of no Session, and executed by tick once the linger expires. Only# settlement cuts live here: the coercive perimeter cut never goes through the# ledger (it must not be cancellable).# A live non-KNOWN Session found at execution time cancels the entry (lazy# guard), so a re-handshake that reused the transport keeps it.self._pending_cuts:dict[str,float]={}# The membership snapshot of the last reconcile, None on an instance with no# perimeter. Read by the one cut that is scheduled on a frame of the peer and# not on the end of a Session, see _send_unknown_session_reply.self._perimeter_membership=None# Pure world membership, owned here so it sits next to the Sessions it gates.# Meaningful only on the world instance, where the Coordinator populates these# from the rendezvous and the world-host writers; inert (empty) on the public# instance. The Coordinator reads them back through membership_snapshot() to build# the per-cycle WorldMembership the perimeter classifies against. The role/addrs# indices and inspector_peer_id stay Coordinator-owned: only the two# sets and the world node's peer-id live here.self.world_agents_set:set=set()self.world_masters_set:set=set()self.world_node_peer_id:str|None=None
The registry and dispatcher of the Sessions of one network.
Argument
Type
Default
Meaning
p2p
P2P
The transport of the network. The manager owns it and hands it to each Session.
p2p_name
str
"p2p_public" or "p2p_world". Every Session and every event carries it.
local_peer_id
str
The peer id of this node on this network. The tie-break of a simultaneous open compares it with the peer id of the peer.
local_node_id
str
The node id of this node.
local_profile_factory
Callable[[], dict]
Returns the current profile of the node as a JSON-serializable dictionary. Each handshake calls it again.
decision_hook
DecisionHook \| None
None
The async policy that accepts or refuses the offer of an initiator and that a world node uses to build a grant (see Session). With None every offer is accepted.
token_verifier
async Callable \| None
None
Verifies the token of a peer and returns (node_id, cv_hash, p2p_peers, exp, code_hash). The node passes NodeConn.verify_token_claims. With None no token is checked.
token_factory
Callable[[], str] \| None
None
Returns the current token of this node. With None no token is sent.
routing_classifier
Callable[[dict, Any], str \| None] \| None
None
Maps a peer info and a membership snapshot to the name of a pool or to None. NodeConn passes a classifier by direction for the public network and one by membership for the world network. With None reconcile classifies nothing.
address_lookup
async Callable \| None
None
Maps a node id to its addresses on the UNaIVERSE server. Every initiator Session receives it and asks it for fresh addresses while it is reconnecting. NodeConn passes it to the public manager only.
The manager keeps two views of its Sessions. The full registry holds at most one Session per peer and includes the KNOWN ones. The active view holds only the Sessions past KNOWN and tick visits this view alone. len(manager) returns the size of the full registry.
Timings of the manager (see Session for the timings of a single Session):
Value
Seconds
Use
Quarantine
25
After a LOST or a FAILED. It stays below the 30 seconds of Custom.REJOINING_WAIT so that the quarantine has expired when a scheduled rejoin runs.
Short quarantine
5
After a FAILED with reason timeout:hello_sent or timeout:hello_ack_sent. Such a failure usually means a slow peer and not a flapping link.
Settlement linger
2
Between the end of a Session and the cut of its connection. A CLOSED with reason local_goaway_acked:... uses 0 because the GOAWAY_ACK proves that nothing is in flight.
Unknown-session linger
10
Between a reply sent to a peer without a Session and the cut of that connection. A HELLO of the peer in the meantime cancels the cut.
The world peer ids of the agents of the world (set[str]). It lives here next to the Sessions whose admission it controls and only the methods of NodeConn that write the roster change it. On the public network it stays empty.
defensure(self,peer_id:str,addresses:list[str],is_world_join:bool=False,remote_node_id_hint:str|None=None,grant:dict|None=None,reject_relay:bool=False,app_role:int=0,dial_attempts:int|None=None,dial_budget_s:float|None=None,)->Session:"""Registers an initiator Session to `peer_id` in the KNOWN state WITHOUT starting it (no dial yet). Idempotent: a non-terminal existing Session is returned unchanged; a FAILED/CLOSED one is replaced. ``activate`` dials it later. This lets a caller know a peer without committing to a connection. Args: peer_id: The peer. addresses: The multiaddrs of the peer. is_world_join: True for the public Session of a world join (default: False). remote_node_id_hint: The node-id expected at the peer, when known (default: None). grant: The grant to redeem, for the world Session of a join (default: None). reject_relay: True to fail a dial that resolves through a relay (default: False). app_role: The applicative world role of the peer (default: 0). dial_attempts: Override of the dial-attempt cap (default: None, module default). dial_budget_s: Override of the CONNECTING budget in seconds (default: None, module default). Returns: The registered (or existing) Session. """existing=self._sessions.get(peer_id)ifexistingisnotNoneandexisting.statenotin(SessionState.FAILED,SessionState.CLOSED):returnexistingsess=Session(peer_id=peer_id,role=SessionRole.INITIATOR,p2p=self.p2p,p2p_name=self.p2p_name,local_peer_id=self.local_peer_id,local_node_id=self.local_node_id,local_profile_factory=self._local_profile_factory,remote_node_id_hint=remote_node_id_hint,addresses=addresses,is_world_join=is_world_join,decision_hook=self._decision_hook,grant=grant,reject_relay=reject_relay,app_role=app_role,token_verifier=self._token_verifier,token_factory=self._token_factory,dial_attempts=dial_attempts,dial_budget_s=dial_budget_s,address_lookup=self._address_lookup,)self._set_known(peer_id,sess)returnsess
Registers an initiator Session to peer_id in the KNOWN state without dialing and returns it. A Session that exists and is not FAILED or CLOSED is returned unchanged and its arguments are ignored. A FAILED or CLOSED one is replaced.
Argument
Type
Default
Meaning
peer_id
str
The peer.
addresses
list[str]
Its addresses.
is_world_join
bool
False
True for the public Session that asks a world for a grant.
remote_node_id_hint
str \| None
None
The node id expected at the peer. A token for another node id fails the handshake.
grant
dict \| None
None
The grant that the world Session of a join redeems.
reject_relay
bool
False
True to fail a dial that reaches the peer only through a relay.
app_role
int
0
The role bits of the peer in the world (see NodeConn.get_role).
dial_attempts
int \| None
None
The number of dial attempts (4 when None).
dial_budget_s
float \| None
None
The total time allowed for the dial in seconds (300 when None).
asyncdefactivate(self,peer_id:str)->list[SessionEvent]:"""Starts the initiator Session for `peer_id`: enters CONNECTING and launches the dial off-task (async). The outcome of the dial — HELLO / retry / FAILED — is reaped by tick_dial. A quarantined peer is refused without dialing. No-op if there is no Session for the peer. Args: peer_id: The peer. Returns: The events from start (always [] today), or a synthetic FAILED event for a quarantined peer. """sess=self._sessions.get(peer_id)ifsessisNone:return[]# Quarantine gate (single dial door): a peer that recently went LOST/FAILED is# refused immediately, without dialing, until its window expires. Non-blocking:# we return FAILED(quarantined) at once and leave the (inert KNOWN) Session in# place, so a later activate after the window can dial it.now=time.monotonic()ban_until=self._quarantine.get(peer_id,0.0)ifban_until>now:# The refusal names the wait in the Session log, not to the person (the browser puts every user line in the# chat of its world): the node layer, which knows what it was dialling, logs the FAILED with its reason.# The reason keeps its "quarantined" prefix (substring/startswith stays robust), and the machine-readable# remainder rides data["retry_after_s"], so a scheduler (the rejoin watchdog) can retry right past the# ban instead of bouncing on a blind cadence.remaining=ban_until-nowlog.session(f"dial to ...{peer_id[-5:]} refused: peer quarantined for {remaining:.1f}s more",sub=self._label)return[SessionEvent(type=SessionEventType.FAILED,session_id="",peer_id=peer_id,role=SessionRole.INITIATOR,p2p_name=self.p2p_name,data={"reason":f"quarantined:{remaining:.1f}s","retry_after_s":remaining},)]log.session(f"activating Session to ...{peer_id[-5:]}",sub=self._label)events=sess.start()# non-blocking: the dial runs off-task, reaped by tick_dialself._promote(peer_id,sess)self._on_terminal(events,now)returnevents
Starts the registered Session of peer_id (async). The Session enters CONNECTING and its dial runs as a background task that a later tick collects. The method returns the events of the start (an empty list in practice) and also an empty list when the peer has no Session.
The quarantine is checked here and only here. Every dial therefore goes through this method. A quarantined peer is not dialed. The method returns one FAILED event with an empty session_id, the reason "quarantined:<seconds>s" and data["retry_after_s"] holding the seconds left. The Session stays KNOWN for a later activate. The rejoin logic of the node reads retry_after_s to retry right after the quarantine ends. initiate and NodeConn (for the dials held by the wait for the roster) call it.
asyncdefinitiate(self,peer_id:str,addresses:list[str],is_world_join:bool=False,remote_node_id_hint:str|None=None,grant:dict|None=None,reject_relay:bool=False,replace_stale:bool=False,dial_attempts:int|None=None,dial_budget_s:float|None=None,hold:bool=False,)->list[SessionEvent]:"""Opens a new initiator Session to `peer_id` and starts it (async). A stale FAILED/CLOSED Session is replaced. initiate() = ensure() + activate(). With ``hold`` the Session is registered with this intent and left KNOWN, for a later ``activate``. Idempotent on a matching-intent non-terminal Session (returns []), BUT a Session whose intent DIVERGES from the request is replaced rather than silently reused: the world-join flag must match, and the Coordinator sets ``replace_stale`` for a spent world-join carrier (an established carrier whose handoff already failed and was rolled back). Otherwise a leftover Session would shadow the dial and the join would never (re)start — the caller sees success while nothing happens. Args: peer_id: The peer. addresses: The multiaddrs of the peer. is_world_join: True for the public Session of a world join (default: False). remote_node_id_hint: The node-id expected at the peer, when known (default: None). grant: The grant to redeem, for the world Session of a join (default: None). reject_relay: True to fail a dial that resolves through a relay (default: False). replace_stale: True to replace a spent world-join carrier (default: False). dial_attempts: Override of the dial-attempt cap (default: None, module default). dial_budget_s: Override of the CONNECTING budget in seconds (default: None, module default). hold: True to register the Session without dialing yet (default: False). Returns: The events of the start (possibly empty). """# The quarantine gate lives in activate() (the single dial door), so a# quarantined peer is refused there, even on a direct activate.existing=self._sessions.get(peer_id)app_role=0ifexistingisnotNoneandexisting.state==SessionState.KNOWN:# A KNOWN is a rendezvous placeholder, not a dial in flight: drop it so the# caller's addresses / grant / is_world_join / hints take effect below. Carry# its rendezvous role across the replacement so the dialed Session is not# blank on app_role until the next sync refresh.app_role=existing.app_roleself._forget(peer_id)elifexistingisnotNoneandexisting.state==SessionState.CLOSING:# A CLOSING Session is not a healthy one to no-op on: its GOAWAY is out# and the relation is ending, so a new dial intent inside its window (up# to 10s) must start a fresh Session — not be swallowed while the caller# is told the dial started. This is the outbound mirror of deliver's# inbound supersede. No farewell is owed (already sent): forget and dial# fresh over the still-live transport. The forgotten FSM emits no CLOSED,# so no settlement cut is scheduled — right, the re-dial owns it now.log.session(f"initiate(...{peer_id[-5:]}): superseding CLOSING Session with a "f"fresh dial",sub=self._label)self._forget(peer_id)elifexistingisnotNoneandexisting.statenotin(SessionState.FAILED,SessionState.CLOSED):ifnotreplace_staleandexisting.is_world_join==is_world_join:log.session(f"initiate(...{peer_id[-5:]}): "f"already have Session in state {existing.state.value} — no-op",sub=self._label)return[]# Intent diverged (world-join vs plain), or a spent carrier: the stale Session# would shadow the new dial, and a bare forget leaves the remote ESTABLISHED,# ignoring our HELLO. GOAWAY-close it (so the remote drops its Session and# answers the new HELLO) and forget it now — without waiting for the CLOSED,# or ensure() below would return the CLOSING — then dial fresh. The transport# is deliberately NOT touched: the live connection is exactly what the re-dial# wants, and a disconnect here would abort the GOAWAY we just queued (the# forgotten Session emits no CLOSED, so no settlement cut is scheduled).log.session(f"initiate(...{peer_id[-5:]}): replacing {existing.state.value} Session "f"(intent diverged or stale carrier)",sub=self._label)awaitself.close_session(peer_id,GRACEFUL_SHUTDOWN)self._forget(peer_id)self.ensure(peer_id,addresses,is_world_join=is_world_join,remote_node_id_hint=remote_node_id_hint,grant=grant,reject_relay=reject_relay,app_role=app_role,dial_attempts=dial_attempts,dial_budget_s=dial_budget_s)ifhold:log.session(f"Session to ...{peer_id[-5:]} registered, its dial held",sub=self._label)return[]log.session(f"initiating Session to ...{peer_id[-5:]}",sub=self._label)returnawaitself.activate(peer_id)
Opens an initiator Session to peer_id and starts it (async). It takes the arguments of ensure (without app_role) plus two more.
Argument
Type
Default
Meaning
replace_stale
bool
False
True to replace an existing Session even when its is_world_join matches. NodeConn.initiate_session passes True for a world join toward a carrier left over from a failed join.
hold
bool
False
True to register the Session and leave it KNOWN without dialing.
The existing Session of the peer decides what happens.
Existing Session
Action
none, FAILED or CLOSED
A new Session is registered and started.
KNOWN
It is forgotten and a new one is registered with the given addresses, grant and flags. The role bits of the old one are carried over.
CLOSING
It is forgotten without a farewell (its GOAWAY is already out) and a new one is dialed over the connection that is still open.
any other state with the same is_world_join and replace_stale=False
Nothing happens and the method returns an empty list.
any other state otherwise
It is closed with a GOAWAY (GRACEFUL_SHUTDOWN) and forgotten at once. A new one is then dialed on the same connection. The connection stays open because a cut would destroy the GOAWAY.
It returns the events of activate (a FAILED for a quarantined peer) or an empty list with hold=True. NodeConn.initiate_session and NodeConn.start_world_handoff call it.
defsync_known_peers(self,known:dict[str,tuple])->None:"""Reconciles the inert KNOWN roster against the peers currently advertised by the rendezvous. Registers a KNOWN Session for every known peer that has no Session yet, refreshes the rendezvous-sourced metadata (addresses + applicative role) on the Sessions that already exist, and prunes KNOWN Sessions whose peer has vanished. The metadata refresh touches a Session's addresses/app_role only, never its FSM state, so an active (established / in-transit) Session keeps running while its role/addrs stay current. Pruning is still KNOWN-only: an ESTABLISHED peer that drops out of the rendezvous keeps its live Session until the transport tears it down, and a FAILED / CLOSED one is left to the normal evict path. KNOWN Sessions live solely in the registry, never in a pool, so this cannot perturb the per-cycle diff or the perimeter. Args: known: The advertised peers, ``peer_id -> (addresses, app_role)``. """forpeer_id,(addrs,app_role)inknown.items():addrs=list(addrs)ifaddrselse[]sess=self._sessions.get(peer_id)ifsessisNone:self.ensure(peer_id,addrs,app_role=app_role)else:sess.addresses=addrssess.app_role=app_rolestale=[pidforpid,sinself._sessions.items()ifs.state==SessionState.KNOWNandpidnotinknown]forpeer_idinstale:self._forget(peer_id)
Aligns the KNOWN Sessions with the peers that the rendezvous advertises. known maps each peer id to (addresses, app_role). A peer with no Session gets a KNOWN one through ensure. A peer with a Session of any state gets its addresses and role refreshed while its state stays untouched. A KNOWN Session whose peer is no longer advertised is forgotten. An ESTABLISHED Session whose peer left the rendezvous keeps running until its transport drops. NodeConn.update calls it on the world manager at every cycle.
defhas_established_world_join_carrier(self,peer_id:str)->bool:"""Tells whether peer_id holds an ESTABLISHED initiator Session opened for a world join. Paired with the Coordinator's pending-handoff view: an established world-join carrier with NO pending handoff is a spent carrier (its private handoff failed and was rolled back, leaving the carrier ESTABLISHED), which the next join attempt must replace rather than reuse. Restricted to ESTABLISHED so an in-flight handshake is never torn down. Args: peer_id: The peer. Returns: True if the peer holds an established world-join carrier. """s=self._sessions.get(peer_id)returnsisnotNoneands.is_world_joinands.state==SessionState.ESTABLISHED
Returns True when the peer has an ESTABLISHED initiator Session opened for a world join. NodeConn.initiate_session combines it with its ledger of joins in flight. A carrier with no join in flight is a leftover of a failed join and must be replaced.
asyncdefdeliver(self,peer_id:str,protocol_id:str,sess_msg:SessMsg)->list[SessionEvent]:"""Routes a Session message at this manager's p2p instance (async). Handles the tie-breaker on inbound HELLO from an unknown / contending peer, and replies on behalf of no Session when we hold none for the peer. Args: peer_id: The sender peer. protocol_id: The Session protocol the message arrived on. sess_msg: The decoded message. Returns: The events generated (already settled, see _on_terminal). """ifprotocol_idnotinSESSION_PROTOCOL_IDS:log.error(f"deliver: unknown protocol {protocol_id}, dropping",sub=self._label)return[]sess=self._sessions.get(peer_id)# A terminal Session must not shadow new traffic from the peer (an# inbound HELLO routed to a dead FSM is silently ignored, blocking any# re-handshake initiated by the remote): evict it and fall through to# the no-session paths.ifsessisnotNoneandsess.statein(SessionState.FAILED,SessionState.CLOSED):self._forget(peer_id)sess=None# A terminal-ADJACENT Session must not shadow a fresh handshake either: a new# inbound HELLO_REQ while we are CLOSING (our GOAWAY still in flight, any# role) or while a RESPONDER rides its reconnect grace is the peer's# declaration that the old session is dead on its side — it re-dialed.# Supersede silently: abort the old FSM (no terminal event; the hosted/pool# state of the old relation survives until the new ESTABLISHED re-enrols it)# and let the HELLO spawn a fresh responder below. These are already-dying# sessions, so no session_id guard is needed.if(sessisnotNoneandprotocol_id==SESSION_HELLO_PROTOCOLandsess_msg.kind==SessMsg.KIND_HELLO_REQand(sess.state==SessionState.CLOSINGor(sess.state==SessionState.RECONNECTINGandsess.role==SessionRole.RESPONDER))):log.session(f"fresh inbound HELLO supersedes stale {sess.state.value} Session "f"for ...{peer_id[-5:]}",sub=self._label)sess.abort_silently("superseded_by_new_hello")self._forget(peer_id)sess=None# Reborn-peer supersede: a HELLO_REQ carrying a NEW session_id while we hold a# session the peer is supposed to still own — ESTABLISHED (either role), or# RECONNECTING as INITIATOR — proves the peer abandoned that session and came# back fresh (a live peer would RESUME the shared id, not send a new HELLO).# Without this the ESTABLISHED FSM silently ignores the HELLO and the initiator# goes to the tie-breaker and may reject the reborn peer; either way recovery# waits ~55s for our own liveness path. The session_id must be NON-EMPTY and# DIFFERENT: a replay of the establishing HELLO carries the same id (falls# through, ignored) and a malformed empty id must never tear down a live session.# abort_silently keeps the transport and the hosted/pool state, re-enrolled when# the fresh responder reaches ESTABLISHED. NB: a genuine simultaneous open lives# in CONNECTING/HELLO_SENT (kept on the tie-breaker), not here.inbound_sid=bytes(sess_msg.get("session_id")orb"")if(sessisnotNoneandprotocol_id==SESSION_HELLO_PROTOCOLandsess_msg.kind==SessMsg.KIND_HELLO_REQandinbound_sidandinbound_sid!=sess.session_idand(sess.state==SessionState.ESTABLISHEDor(sess.state==SessionState.RECONNECTINGandsess.role==SessionRole.INITIATOR))):log.session(f"fresh inbound HELLO (new session_id) supersedes stale "f"{sess.state.value} Session for ...{peer_id[-5:]} (reborn peer)",sub=self._label)sess.abort_silently("superseded_by_reborn_hello")self._forget(peer_id)sess=None# A KNOWN Session could be an initiator that has not dialed yet: it is not an# in-flight handshake, so route inbound traffic as if there were no Session.# The peer dialed us first, so an inbound HELLO makes us the responder# (spawn_responder overwrites the KNOWN registry entry); a KNOWN never reaches# the tie-breaker below because it didn't dial yet, and on PING/RESUME# the no-session path replies "unknown session" while the KNOWN intent stays put for a later dial.ifsessisNoneorsess.state==SessionState.KNOWN:ifprotocol_id==SESSION_HELLO_PROTOCOLandsess_msg.kind==SessMsg.KIND_HELLO_REQ:# Unknown peer, or a KNOWN intent that never dialed → spawn a responder# Session (no tie-breaker possible: no in-flight initiator for them).sess=self._spawn_responder(peer_id)elif(protocol_id==SESSION_CONTROL_PROTOCOLandsess_msg.kindin(SessMsg.KIND_PING,SessMsg.KIND_RESUME,SessMsg.KIND_GOAWAY)):# We are (most likely) the restarted/forgetful peer: we hold no# Session for this session_id. Tell the remote so it stops waiting# instead of dropping silently: PING/RESUME get "unknown session" so# the initiator re-handshakes rather than riding its grace to LOST;# a GOAWAY gets a GOAWAY_ACK so the remote's CLOSING ends in one RTT# instead of its full timeout (it already forgot us, no Session to tear# down here). Only the manager knows "no Session for this peer", so it# also settles the transport, which no Session will.awaitself._send_unknown_session_reply(peer_id,sess_msg)return[]else:log.session(f"{protocol_id}/{sess_msg.kind} from unknown peer "f"...{peer_id[-5:]} — dropped",sub=self._label)return[]# Tie-breaker — only when the inbound is a competing HelloRequest (its# explicit kind tag distinguishes it from the HelloResponse coming back to# our own dial; both travel on the same protocol_id). A KNOWN Session is also# role=INITIATOR, but it is not an in-flight dial: the state guard keeps it out# of the tie-breaker (and the no-session branch above has already handled it).# Only a genuine simultaneous open (both sides first-dialing) reaches here:# RECONNECTING is not eligible — an initiator in reconnect re-dials with RESUME,# not a HELLO, so an inbound HELLO there is a reborn peer handled just above.elif(protocol_id==SESSION_HELLO_PROTOCOLandsess_msg.kind==SessMsg.KIND_HELLO_REQandsess.role==SessionRole.INITIATORandsess.statein(SessionState.CONNECTING,SessionState.HELLO_SENT)):events=awaitself._handle_simultaneous_open(peer_id)ifevents=="_proceed_with_existing_":# type: ignore[comparison-overlap]# We kept the existing initiator; the inbound HELLO is dropped after# we wrote a soft-reject to the peer (handled inside the helper).return[]elifevents=="_replaced_with_responder_":# type: ignore[comparison-overlap]sess=self._sessions[peer_id]# Fall through and process the inbound HELLO against the new responder.else:returnevents# type: ignore[return-value]events=awaitsess.process_inbound(protocol_id,sess_msg)self._on_terminal(events)returnevents
Routes one inbound Session frame and returns the events it produced (async). peer_id is the sender as the transport verified it, protocol_id the Session protocol of the frame and sess_msg the decoded SessMsg. A protocol that is not a Session protocol is logged and dropped. The rules apply in this order.
A FAILED or CLOSED Session of the peer is forgotten. Without this a HELLO of the peer would reach a dead state machine and the peer could never start over.
A HELLO received while the Session is CLOSING (any role) or while a responder Session is RECONNECTING replaces that Session. The peer dialed again and its old Session is dead on its side. The old Session is aborted without an event and the HELLO spawns a new responder. The peer stays among the known agents of the node until the new Session reaches ESTABLISHED.
A HELLO with a non-empty session_id different from the current one replaces an ESTABLISHED Session (any role) or a RECONNECTING initiator in the same way. Such a peer restarted. A live peer would have sent RESUME with the shared id. A replay of the HELLO that established the Session carries the same id and is ignored.
A HELLO toward no Session or a KNOWN one spawns a responder Session that overwrites the KNOWN entry. A PING, a RESUME or a GOAWAY gets the reply for a peer without a Session (see below) and leaves a KNOWN entry in place. Any other frame is dropped.
A HELLO toward an initiator in CONNECTING or HELLO_SENT is a simultaneous open and the tie-break below resolves it.
Otherwise the Session processes the frame.
This reply tells the peer at once that this node holds no Session for it. Without it the peer would wait for its own timeouts.
Frame
Answer
PING
PONG with ok=False and the same session_id and nonce. The peer treats it as a hard failure of its Session.
RESUME
RESUME_ACK with accepted=False and SESSION_UNKNOWN. An initiator then runs a new handshake.
GOAWAY
GOAWAY_ACK with received=True. The CLOSING Session of the peer ends in one round trip.
After the reply the manager schedules the cut of the connection of the peer 10 seconds later. A peer that starts over has this time to send its HELLO and a HELLO cancels the cut. A pending cut makes reconcile skip the peer and any peer could keep the cut pending by sending such frames again. On the world network a peer outside the membership therefore gets no scheduled cut and the next reconcile cuts it.
The tie-break of a simultaneous open compares the two peer ids as strings. The node with the smaller peer id keeps its initiator Session. It drops the inbound HELLO and answers it with a HELLO_ACK that carries SIMULTANEOUS_OPEN_LOSS. The node with the larger peer id aborts its initiator without an event, spawns a responder and processes the HELLO. When the refusal reaches an initiator that is still waiting in HELLO_SENT, that initiator fails with reason hello_ack_rejected:SIMULTANEOUS_OPEN_LOSS and its peer enters quarantine on that node. The connection carries the handshake of the winner and no settlement cut follows such a failure.
The terminal events are settled before they are returned (see tick). NodeConn.pump_sessions and NodeConn.drain_teardown call it.
asyncdeftick(self,now:float|None=None)->list[SessionEvent]:"""Sweeps all Sessions: timeout firings + active re-dial + session-level keep-alive (async). It then settles this sweep's terminal events and executes the settlement cuts whose linger expired. Single dispatch path; the returned list is what node.py acts on (already settled, see _on_terminal). Args: now: The current monotonic time, or None to read it here (default: None). Returns: The events generated by the sweep. """ifnowisNone:now=time.monotonic()events:list[SessionEvent]=[]# Our root token refreshed (token_factory reflects self.node_token): push it# in-band to every ESTABLISHED peer so their cached expiry advances without a# re-handshake. Detected by comparing against the last pushed value.ifself._token_factoryisnotNone:tok=self._token_factory()iftok!=self._last_pushed_token:self._last_pushed_token=tokforsessinlist(self._active_sessions.values()):awaitsess.send_token_update(tok)# Snapshot of values; mutation during iteration is safe because we operate# on the snapshot only (per-session state changes happen synchronously and# don't add new sessions inside tick).forsessinlist(self._active_sessions.values()):t_event=sess.check_timeout(now)ift_eventisnotNone:events.append(t_event)events.extend(awaitsess.tick_dial(now))k_event=awaitsess.tick_keepalive(now)ifk_eventisnotNone:events.append(k_event)# Reap quarantine entries that have expired (cheap; bounded by peer count).ifself._quarantine:expired=[pidforpid,tinself._quarantine.items()ift<=now]forpidinexpired:self._quarantine.pop(pid,None)# Settle the terminal events of this sweep (quarantine + forget + cut ledger).self._on_terminal(events,now)# Execute the settlement cuts whose linger expired: the deferred transport# teardown of peers whose Session already ended. A live non-KNOWN Session# found now cancels the cut (lazy guard): a re-handshake (re-dial, supersede,# replace-stale) reuses the transport and owns it again. A KNOWN placeholder# does NOT cancel — it is rendezvous metadata, not a live relation, and# keeping the half-open transport would defeat the cut.ifself._pending_cuts:due=[pidforpid,deadlineinself._pending_cuts.items()ifdeadline<=now]forpidindue:delself._pending_cuts[pid]sess=self._sessions.get(pid)ifsessisnotNoneandsess.statenotin(SessionState.KNOWN,SessionState.FAILED,SessionState.CLOSED):log.session(f"settlement cut for ...{pid[-5:]} cancelled: live Session "f"({sess.state.value})",sub=self._label)continue# The relation is over: what is still queued for the peer goes with its transport, or its writer would# dial the peer again and deliver frames nobody waits for (a purge inside the settlement window keeps# them, and after a LOST no settled purge may follow)dropped=self.drop_send_queue(pid)awaitself.p2p.disconnect(pid)log.session(f"settlement cut executed for ...{pid[-5:]}"+(f", {dropped} queued messages dropped"ifdropped>0else""),sub=self._label)returnevents
Sweeps the active Sessions and returns their events (async). When now is None the method reads time.monotonic() itself.
When the token of this node changed since the last push, every ESTABLISHED Session sends a TOKEN_UPDATE with the new token. The peers then extend their record of its expiry without a new handshake.
For each active Session it calls check_timeout, tick_dial and tick_keepalive in this order (see Session).
It removes the expired quarantine entries.
It settles the terminal events of the sweep.
It executes the settlement cuts whose linger expired. A new handshake reuses the connection and a live Session of the peer (any state other than KNOWN, FAILED and CLOSED) therefore cancels the cut. A KNOWN Session does not cancel it. Before the disconnect the send queue of the peer is emptied. A writer of that queue would otherwise dial the peer again to deliver frames nobody waits for.
Settling a terminal event means three steps. deliver, tick and on_peer_disconnected all apply them before they return their events.
A LOST or a FAILED puts the peer in quarantine for 25 seconds. A FAILED with reason timeout:hello_sent or timeout:hello_ack_sent uses 5 seconds. A FAILED of a Session that redeems a world grant is not quarantined. The next grant arrives with the next join and a quarantine would only refuse its redemption.
The dead Session is forgotten. The FAILED event of a quarantine refusal has no Session behind it and changes nothing here.
A settlement cut is scheduled after the linger of 2 seconds. A CLOSED whose reason starts with local_goaway_acked is cut at the next tick. A reason that contains SIMULTANEOUS_OPEN_LOSS gets no cut. A new event overwrites the deadline of a previous one.
Because the settlement runs before the events reach the node, the purge that the node sends back down for the same peer finds a cut pending. drop then does nothing and cannot destroy the farewell written moments earlier. NodeConn.pump_sessions and NodeConn.drain_teardown call it.
asyncdefon_peer_disconnected(self,peer_id:str)->list[SessionEvent]:"""Handles a peer dropping, as reported by the polled libp2p diff (async). Args: peer_id: The peer. Returns: The events generated (a FAILED event for a handshake in flight, RECONNECTING, or none). """sess=self._sessions.get(peer_id)ifsessisNone:return[]# CONNECTING is not here: it has no handshake on any connection yet, its own dial# decides, and a dial that failed is tried again. A connection that its dial was# handed and that carried no HELLO is such a failed dial, and its drop, reported# a moment later, must not fail and quarantine the attempt that follows.ifsess.statein(SessionState.HELLO_SENT,SessionState.HELLO_ACK_SENT,SessionState.PROFILE_SENT,SessionState.AWAITING_WORLD_GRANT):# Handshake can't continue without a live connection — fail fast.# AWAITING_HANDOFF is deliberately NOT here: the parked grant carrier# tolerates transport blips (the joiner's re-dial + RESUME is accepted# in that state, and failing it here would quarantine the joiner and# collapse the handoff on any blip the poll can see); its 30s timeout# is the backstop. on_transport_disconnected below no-ops for it.ev=sess._fail("connection_dropped_during_handshake")self._on_terminal([ev])return[ev]ev=sess.on_transport_disconnected()return[ev]ifevisnotNoneelse[]
Reacts to the transport losing a peer and returns the resulting events (async). A Session in HELLO_SENT, HELLO_ACK_SENT, PROFILE_SENT or AWAITING_WORLD_GRANT fails at once with reason connection_dropped_during_handshake and the failure is settled here (quarantine, forget, cut). An ESTABLISHED Session enters RECONNECTING and a RECONNECTING one restarts its reconnect window (see Reconnection). A connection that dropped before carrying a HELLO is only a failed dial attempt. A CONNECTING Session is therefore left to its own dial logic. An AWAITING_HANDOFF Session tolerates the drop until its timeout of 30 seconds. NodeConn.on_peer_disconnected calls it.
asyncdefon_peer_reconnected(self,peer_id:str)->list[SessionEvent]:"""Handles a peer reappearing in the polled libp2p diff (async). Args: peer_id: The peer. Returns: The events generated (possibly empty). """sess=self._sessions.get(peer_id)ifsessisNone:return[]ev=sess.on_transport_reconnected()return[ev]ifevisnotNoneelse[]
Reacts to the transport seeing a peer again and returns the resulting events (async). Only a RECONNECTING Session reacts and the reaction produces no event. An initiator marks a RESUME as pending and a responder sends a probe on its next tick. A peer with no Session gives an empty list. NodeConn.on_peer_reconnected calls it.
asyncdefclose_session(self,peer_id:str,reason_code:int=GRACEFUL_SHUTDOWN,)->list[SessionEvent]:"""Closes the Session of a peer with a GOAWAY (async). Args: peer_id: The peer. reason_code: The reason code carried by the GOAWAY (default: GRACEFUL_SHUTDOWN). Returns: An empty list: the CLOSED event arrives later via process_inbound(GoawayAck) or tick. """sess=self._sessions.get(peer_id)ifsessisNone:log.session(f"close_session(...{peer_id[-5:]}): no Session — no-op",sub=self._label)return[]awaitsess.close(reason_code)return[]# CLOSED event will arrive via process_inbound(GoawayAck) or tick
Sends a GOAWAY with reason_code (default GRACEFUL_SHUTDOWN) through the Session of the peer (async). The Session closes only from ESTABLISHED, RECONNECTING or AWAITING_HANDOFF and ignores the call in any other state. For a peer with no Session the call does nothing. It always returns an empty list because the CLOSED event arrives later with the GOAWAY_ACK or after the closing timeout of 10 seconds. drop, initiate and NodeConn.complete_world_handoff call it.
asyncdefdrop(self,peer_id:str,reason_code:int|None=None)->list[SessionEvent]:"""Tears the relation down on THIS instance, dispatching on the Session state (async). The transport follows the Session's terminal state — never a disconnect in the same stack as a farewell write (P2P.disconnect is abortive and would destroy the GOAWAY/ACK just queued): * already tearing down (CLOSING, or a settlement cut pending — which implies nothing live behind it: a live Session cancels the entry eagerly at birth) → no-op: makes the frequent double-purge (a CLOSED dispatched after an earlier purge) idempotent WITHOUT aborting the farewell in flight; * ESTABLISHED/RECONNECTING/AWAITING_HANDOFF with a reason → GOAWAY-close only; the deferred settlement cut severs the transport once the CLOSED lands (ACK or the CLOSING timeout); * KNOWN → forget the placeholder and sever any half-open transport now (there is no GOAWAY owed to a peer we never handshaked; the disconnect is a Go no-op when nothing is connected, and it is the only cure for a chat-only/half-open peer whose Session never went past KNOWN); * any other live Session (mid-handshake, or a live Session dropped with no reason) → silent coercive teardown: abort, forget, disconnect now — a purge must abort a handshake, not leave it running to completion; * no Session (or a stale terminal one) → disconnect now: nothing will ever settle this transport, and this is the only cure for a half-open peer. The manager owns its P2P handle, so the conn layer never reaches the transport directly (Node -> NodeConn -> SM -> P2P); the disconnect is best-effort (an error means 'gone'). Args: peer_id: The peer. reason_code: The reason code of the GOAWAY, or None for a teardown with no farewell (default: None). Returns: The close events (always []: the CLOSED arrives later via tick/ACK). """sess=self._sessions.get(peer_id)ifsessisnotNoneandsess.state==SessionState.CLOSING:log.session(f"drop(...{peer_id[-5:]}): already tearing down — no-op",sub=self._label)return[]ifpeer_idinself._pending_cuts:# A pending settlement cut implies nothing live past a KNOWN placeholder# behind it (a live Session cancels the entry eagerly at birth, see# _set_active/_promote): this is the frequent double-purge, a no-op that# must not abort the farewell in flight.log.session(f"drop(...{peer_id[-5:]}): already tearing down — no-op",sub=self._label)return[]ifsessisNoneorsess.statein(SessionState.FAILED,SessionState.CLOSED):ifsessisnotNone:self._forget(peer_id)awaitself.p2p.disconnect(peer_id)return[]ifsess.state==SessionState.KNOWN:self._forget(peer_id)awaitself.p2p.disconnect(peer_id)return[]ifreason_codeisnotNoneandsess.statein(SessionState.ESTABLISHED,SessionState.RECONNECTING,SessionState.AWAITING_HANDOFF):returnawaitself.close_session(peer_id,reason_code)sess.abort_silently(f"dropped:{reason_name(reason_code)ifreason_codeisnotNoneelse'no_reason'}")self._forget(peer_id)awaitself.p2p.disconnect(peer_id)return[]
Tears down the relation with a peer on this network according to the state of its Session (async). reason_code is a reason code of sess_msg or None for a teardown without farewell. It always returns an empty list.
State of the Session
Action
CLOSING or with a settlement cut pending for the peer
Nothing. The teardown is already in flight and a second purge must not destroy its farewell.
none, FAILED or CLOSED
The Session (if any) is forgotten and the connection is cut now.
KNOWN
The Session is forgotten and the connection is cut now. No farewell is owed to a peer that never completed a handshake.
ESTABLISHED, RECONNECTING or AWAITING_HANDOFF with a reason
close_session sends a GOAWAY. The settlement cut closes the connection once the CLOSED event arrives.
any other live state or a live Session with no reason
The Session is aborted without an event and forgotten. The connection is cut now.
The cut is a disconnect that never raises (an error means that the peer is gone already). NodeConn.drop_peer calls it and so does the handoff ledger to abort a redemption.
asyncdefclose_all(self,reason_code:int=GRACEFUL_SHUTDOWN)->list[SessionEvent]:"""Sends a GOAWAY to every Session that can be gracefully closed, aborting the others (async). Used on node/runner shutdown so peers see a clean CLOSED instead of falling through liveness-timeout. Sessions already CLOSING/CLOSED (e.g. an intentional world-handoff GOAWAY) are left alone; every other non-terminal state (a handshake in flight, a KNOWN placeholder) is aborted silently and forgotten — no farewell is owed mid-handshake, and the shutdown drain must be able to reach 'nothing closing, nothing pending' instead of waiting on FSMs nobody will ever pump again. Args: reason_code: The reason code carried by the GOAWAYs (default: GRACEFUL_SHUTDOWN). Returns: An empty list: the CLOSED events arrive later. """forpeer_id,sessinlist(self._sessions.items()):ifsess.statein(SessionState.CLOSING,SessionState.CLOSED,SessionState.FAILED):continueifsess.statein(SessionState.ESTABLISHED,SessionState.RECONNECTING,SessionState.AWAITING_HANDOFF):try:awaitsess.close(reason_code)exceptExceptionase:log.error(f"close_all: close(...{sess.peer_id[-5:]}) failed: {e}",sub=self._label)else:sess.abort_silently("shutdown")self._forget(peer_id)return[]
Ends every Session at shutdown (async). A Session in ESTABLISHED, RECONNECTING or AWAITING_HANDOFF sends a GOAWAY with reason_code (default GRACEFUL_SHUTDOWN). The peers then see a clean CLOSED instead of losing the link. A Session already CLOSING, CLOSED or FAILED is left untouched. Every other Session (a handshake in flight, a KNOWN one) is aborted without an event and forgotten. No farewell is owed in the middle of a handshake and the drain of the shutdown must be able to finish. An error while closing one Session is logged and the next one is still closed. It returns an empty list. NodeConn.close_all_sessions calls it.
defhas_pending_teardown(self)->bool:"""Tells whether a farewell is still in flight on this instance. That is a CLOSING Session waiting its GOAWAY_ACK, or a settlement cut not yet executed. The shutdown drain polls this to know when the goodbyes are done. Returns: True while a teardown is in flight. """returnbool(self._pending_cuts)orany(s.state==SessionState.CLOSINGforsinself._active_sessions.values())
Returns True while a Session is CLOSING or a settlement cut is pending. NodeConn.drain_teardown polls it to know when the farewells are done.
defis_tearing_down(self,peer_id:str)->bool:"""Tells whether this peer's teardown is in flight. Its Session is CLOSING (a GOAWAY awaiting its ACK) or a settlement cut is pending in the ledger. reconcile skips such peers (no pool re-admission during the linger, no second cut) and the shutdown drain waits on them. Args: peer_id: The peer. Returns: True while the peer's teardown is in flight. """sess=self._sessions.get(peer_id)return(peer_idinself._pending_cutsor(sessisnotNoneandsess.state==SessionState.CLOSING))
Returns True while the teardown of the peer is in flight. Its Session is then CLOSING or a settlement cut is pending for it. reconcile skips such a peer and NodeConn.drop_peer leaves its send queue untouched.
defclose_transport(self)->None:"""Shuts down this instance's transport (the Go host), freeing its slot. Terminal: only the shutdown path calls it, after the drain. """self.p2p.close()
Closes the transport of this network and frees its slot in the native networking library. Every remaining connection is cut abortively. Only NodeConn.close_transports calls it after the drain.
defget_session(self,peer_id:str)->Session|None:"""Gets the Session of a peer. Args: peer_id: The peer. Returns: The Session, or None if there is none. """returnself._sessions.get(peer_id)
Returns the Session of a peer (any state, KNOWN included) and None when the peer has none.
defis_established(self,peer_id:str)->bool:"""Tells whether the Session of a peer is ESTABLISHED. Args: peer_id: The peer. Returns: True if the peer has an ESTABLISHED Session. """s=self._sessions.get(peer_id)returnsisnotNoneands.state==SessionState.ESTABLISHED
Returns True when the Session of the peer is ESTABLISHED.
defall_established_peer_ids(self)->list[str]:"""Gets the peers whose Session is ESTABLISHED. Returns: The list of their peer IDs. """return[pidforpid,sinself._sessions.items()ifs.state==SessionState.ESTABLISHED]
Returns the list of the peers whose Session is ESTABLISHED.
defis_in_grace(self,peer_id:str)->bool:"""Tells whether this peer's Session is riding its reconnect grace window (RECONNECTING). Disconnected at the transport level but not yet gone. The Coordinator aggregates this across its instances so the Node can choose pool-remove (keep the enrolment across the blip) vs full purge without reaching into Session state itself. Args: peer_id: The peer. Returns: True if the peer's Session is RECONNECTING. """sess=self._sessions.get(peer_id)returnsessisnotNoneandsess.state==SessionState.RECONNECTING
Returns True when the Session of the peer is RECONNECTING. NodeConn.is_in_grace aggregates it over both networks.
defis_handshake_in_flight(self,peer_id:str)->bool:"""Tells whether this peer has a Session whose FIRST handshake is still in flight. It exists but has never reached ESTABLISHED, and is neither a rendezvous-only KNOWN nor RECONNECTING (already established once) nor terminal (FAILED/CLOSED). This is the session-era 'connected but not yet managed' notion the Coordinator aggregates for Agent.agents_are_waiting. The classification lives here, next to SessionState, so the Coordinator stays free of the session enum. Args: peer_id: The peer. Returns: True while the first handshake of the peer is in flight. """sess=self._sessions.get(peer_id)ifsessisNone:returnFalsereturnsess.statenotin(SessionState.KNOWN,SessionState.ESTABLISHED,SessionState.RECONNECTING,SessionState.FAILED,SessionState.CLOSED)
Returns True when the peer has a Session whose first handshake is in flight. Its state is then none of KNOWN, ESTABLISHED, RECONNECTING, FAILED and CLOSED. NodeConn.is_peer_session_pending aggregates it over both networks.
defhas_active_sessions(self)->bool:"""Tells whether any Session is ESTABLISHED or riding its reconnect grace. The Node uses this to keep the main loop at full speed: the keep-alive RTT window assumes a responsive pump, so a node with live sessions must never be treated as idle. Returns: True if there is at least one live Session. """returnany(s.statein(SessionState.ESTABLISHED,SessionState.RECONNECTING)forsinself._active_sessions.values())
Returns True when at least one Session is ESTABLISHED or RECONNECTING.
defrequires_fast_clock(self)->bool:"""Tells whether any Session needs the main loop at full speed. Every tick-active state except the terminals FAILED and CLOSED (KNOWN Sessions are never in the tick-active view, so they are excluded for free). Unlike has_active_sessions, which counts only ESTABLISHED/RECONNECTING, this also covers handshakes in flight (CONNECTING/HELLO_*/PROFILE_SENT/AWAITING_*) and CLOSING, whose RTT-sized timers would be starved by a slowed clock. Returns: True if some Session needs the fast clock. """returnany(s.statenotin(SessionState.FAILED,SessionState.CLOSED)forsinself._active_sessions.values())
Returns True when an active Session is in any state other than FAILED and CLOSED. Unlike has_active_sessions it also counts the handshakes in flight and the CLOSING Sessions, whose timers are sized for a main loop at full speed. NodeConn.requires_fast_clock aggregates it over both networks.
defattested_peers(self,peer_id:str)->tuple:"""The peer-ids that the verified token of this peer's Session attests (empty with no Session or no verifier). Args: peer_id: The peer. Returns: The attested peer-ids. """sess=self._sessions.get(peer_id)returnsess.remote_p2p_peersifsessisnotNoneelse()
Returns the peer ids listed in the verified token that the peer presented in its Session (the peer ids of that node on both networks). It returns an empty tuple when the peer has no Session or no token was verified. NodeConn.start_world_handoff uses it to decide whether a grant may lift a quarantine.
deflift_quarantine(self,peer_id:str)->bool:"""Lets the next dial toward this peer through its quarantine. Args: peer_id: The peer. Returns: True if the peer was quarantined. """returnself._quarantine.pop(peer_id,None)isnotNone
Removes the quarantine of a peer and returns True when the peer was quarantined. NodeConn.start_world_handoff calls it on the world manager for the world peer named in a grant. The grant proves that the world is up and admits the agent.
asyncdefreconcile(self,connected_peer_infos:list|None,membership:Any)->dict:"""Classifies this instance's connected peers into pools (async). Uses the injected per-instance classifier. When a membership snapshot is given (the world instance) an unclassifiable peer is cut from the perimeter with the COERCIVE cut: the reconcile cannot tell a revoked ex-member from an intruder, so the mesh isolation (I-1) wins over a graceful goodbye and the transport is severed at once. The public instance has no membership and never cuts (an undefined-direction peer is simply skipped) — the coercive path is de facto world-instance only. Peers already tearing down (CLOSING, or holding a pending settlement cut) are skipped BEFORE classification: they must not be re-admitted to the pools during their linger, nor cut a second time; the pool diff the Coordinator computes stays identical to the pre-settlement one. Empty pools are absent from the result: the Coordinator iterates its own pools and treats a missing pool as empty, so removals are still detected. Args: connected_peer_infos: The peer infos of the connected peers (None when unknown). membership: The world membership snapshot, or None on an instance with no perimeter. Returns: The dictionary ``pool_name -> {peer_id -> peer_info}``. """classified:dict={}self._perimeter_membership=membershipifconnected_peer_infosisNoneorself._routing_classifierisNone:returnclassifiedseen:set=set()forcinconnected_peer_infos:seen.add(c['id'])ifself.is_tearing_down(c['id']):continuepool_name=self._routing_classifier(c,membership)ifpool_nameisNone:ifmembershipisnotNone:log.session(f"perimeter: cutting unclassifiable peer ...{c['id'][-5:]}",sub=self._label)awaitself._coercive_cut(c['id'])continueclassified.setdefault(pool_name,{})[c['id']]=c# connected_peer_infos only holds peers that opened a stream, so a peer whose only# traffic is a topic subscription is absent above yet still receives every broadcast.# On the world instance, also cut the non-member subscribers the stream loop did not# handle. These inform only the cut, never pool admission (which stays stream-driven),# so we pass bare ids and build no pool entries. Direction does not affect the member# test, so a synthetic value reuses the classifier. Relays never subscribe.ifmembershipisnotNone:forpeer_idinself.topic_peers():ifpeer_idinseenorpeer_id==self.local_peer_idorself.is_tearing_down(peer_id):continue# already classified/cut by the stream loop, ourselves, or leavingifself._routing_classifier({'id':peer_id,'direction':'inbound'},membership)isNone:log.session(f"perimeter: cutting pubsub-only non-member ...{peer_id[-5:]}",sub=self._label)awaitself._coercive_cut(peer_id)returnclassified
Classifies the connected peers of this network into pools and returns dict[str, dict[str, dict]] from a pool name to the peer infos of its peers (async). Empty pools are absent from the result. connected_peer_infos is the list from connected_peers_info() and membership the WorldMembership of the cycle (None on the public network). With no peer list or no classifier the result is empty.
A peer whose teardown is in flight is skipped before classification. It must not come back into a pool during its linger nor be cut twice. Every other peer goes through the classifier. When the classifier returns None the manager of the public network skips the peer and the manager of the world network applies the coercive cut. On the world network the method then checks the peers that are subscribed to the broadcast channels of this node without having opened a stream. Those peers receive every broadcast but are missing from the connected list. Each of them that the membership does not list is cut too.
The coercive cut aborts the Session of the peer without an event, forgets it, puts the peer in quarantine for 25 seconds and disconnects it at once. A hostile peer would ignore a farewell and the isolation of the world cannot wait for a round trip. The coercive cut therefore sends no GOAWAY and schedules no cut. The cut peer discovers the cut by itself through its RESUME, the refusal SESSION_UNKNOWN and its own LOST. NodeConn.update calls it at every cycle.
NodeConn reaches the transport of a network only through these methods. The ones that wait for the network are async and the transport runs them off the event loop. The instantaneous ones are synchronous.
asyncdefsend(self,channel:str,msg:Any)->int|None:"""Sends a direct message through this instance's transport (async). The chat egress passes a Msg object (not bytes): the codec and the thread offload live in P2P. Args: channel: The direct-message channel. msg: The message object. Returns: What the transport returns: the sequence number of the queued message, or None (no send queues, or the browser transport). """returnawaitself.p2p.send(channel,msg)
Sends a direct Msg on channel (async). It returns the sequence number of the message in the send queue of its peer and None when the transport has no send queues. The errors of the transport (P2PError and its subclass for a full queue) propagate to the caller. NodeConn.send and NodeConn.send_tracked call it.
asyncdefbroadcast(self,channel:str,msg:Any)->None:"""Publishes a message on a topic through this instance's transport (async). Args: channel: The pubsub channel. msg: The message object. """awaitself.p2p.broadcast(channel,msg)
Publishes a Msg on the broadcast channel channel (async). Errors of the transport propagate. NodeConn.publish calls it.
defdrop_send_queue(self,peer_id:str)->int:"""Empties the send queue of a peer on this instance's transport (a no-op where there is none). Args: peer_id: The peer. Returns: How many queued messages were dropped. """drop=getattr(self.p2p,"drop_send_queue",None)returndrop(peer_id)ifdropisnotNoneelse0
Empties the send queue of a peer and returns the number of messages dropped (0 on a transport without queues). NodeConn.drop_peer and the settlement cut call it.
defpop_send_events(self)->list[dict]:"""Pops the events of the send queues of this instance's transport (none where there are no queues). Returns: The list of the events, oldest first. """pop=getattr(self.p2p,"pop_send_events",None)returnpop()ifpopisnotNoneelse[]
Pops the events of the send queues of this network in the order of their arrival (an empty list on a transport without queues). NodeConn.pop_send_events calls it.
defset_peer_capabilities(self,peer_id:str,capabilities:int,max_message_size:int|None,max_file_size:int|None=None)->None:"""Tells this instance's transport what a peer can receive (a no-op on a transport that does not care). Args: peer_id: The peer. capabilities: The CAP_* bits of its HELLO / HELLO_ACK. max_message_size: The largest message it takes, from its profile (0: no limit; None or absent: legacy). max_file_size: The largest file it takes, from its profile (0 or None: no limit). """setter=getattr(self.p2p,"set_peer_capabilities",None)ifsetterisnotNone:setter(peer_id,capabilities,max_message_size,max_file_size)
Tells the transport what a peer can receive. capabilities holds the capability bits of its HELLO (see sess_msg). max_message_size is the largest message it accepts (0 means no limit and None an older peer with the legacy limit of 50 MB). max_file_size is the largest file it accepts (0 or None means no limit). A transport that does not use them ignores the call. NodeConn.pump_sessions calls it on every ESTABLISHED and RESUMED event.
defrequest_keepalive_probe(self,peer_id:str)->None:"""Asks the Session of a peer for its next keep-alive PING now, instead of at the end of the period. For a send that failed: a dead peer is then confirmed within the RTT window instead of up to a period later. Args: peer_id: The peer. """sess=self._sessions.get(peer_id)ifsessisnotNone:sess.request_early_ping()
Makes the next keep-alive PING of the Session of the peer due at once (see Session.request_early_ping). A peer with no Session is ignored. NodeConn.request_keepalive_probe calls it after a failed write.
defsubscribe_to_topic(self,channel:str)->None:"""Subscribes this instance to a topic (passthrough to the transport). Args: channel: The pubsub channel. """self.p2p.subscribe_to_topic(channel)
Subscribes this network to the broadcast channel channel. Errors of the transport propagate. NodeConn.subscribe calls it.
defunsubscribe_from_topic(self,channel:str)->None:"""Unsubscribes this instance from a topic (passthrough to the transport). Args: channel: The pubsub channel. """self.p2p.unsubscribe_from_topic(channel)
Unsubscribes this network from the broadcast channel channel. NodeConn.unsubscribe calls it.
asyncdefreserve(self,peer_id:str)->str|None:"""Reserves a slot on a relay through this instance's transport (async). Args: peer_id: The relay peer. Returns: The expiry of the reservation (ISO string), or None when no slot was granted. """returnawaitself.p2p.reserve(peer_id)
Reserves a slot on the relay peer_id and returns the expiry of the reservation as an ISO 8601 string (async). A refusal raises P2PError. NodeConn.reserve calls it (see Relays).
defset_turn_credentials(self,ice_turn_servers:list)->None:"""Updates this instance's TURN credentials (passthrough). Sync: it is a local ICE config update for future WebRTC connections, not a network round-trip. Args: ice_turn_servers: The TURN server descriptions. """self.p2p.set_turn_credentials(ice_turn_servers)
Hands the transport 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. Only the connections opened afterward use them. NodeConn.set_turn_credentials calls it.
defconnected_peers_info(self)->list|None:"""Gets the transport-level connected peers on this instance (passthrough). The Coordinator reads peer info through the manager instead of reaching into the P2P handle. None on an FFI error (transport state unknown), so a transient failure is not read as "zero peers": the reconcile skips the diff on None instead of emptying the pools. Returns: The list of the connected peer infos, or None when the transport state is unknown. """returnself.p2p.get_connected_peers_info()
Returns the peer infos of the peers connected to this network at the transport level. Each one is a dictionary with keys such as id, addrs and direction ("inbound" or "outbound"). A None return means that the transport could not answer. reconcile then skips the cycle instead of reading "no peers".
deftopic_peers(self)->list:"""Gets the peer IDs subscribed to this instance's topics (passthrough). They are the directly-connected peers that receive its broadcasts. The world perimeter uses them to see the pubsub-only peers that open no stream and so never appear in connected_peers_info. Empty on transport error, so a transient FFI failure never causes a spurious cut. Returns: The list of the peer IDs. """returnself.p2p.get_topic_peers()
Returns the peer ids of the directly connected peers subscribed to any broadcast channel of this network. A transport that could not answer gives an empty list and a failure never causes a cut. reconcile uses it on the world network.
defrendezvous_peers(self)->dict|None:"""Gets the rendezvous advertisement snapshot on this instance (passthrough). Meaningful only on the world instance, where the rendezvous is joined; inert (None) on the public one. The Coordinator parses and stores the result, the manager only fetches it. Returns: The rendezvous snapshot, or None. """returnself.p2p.get_rendezvous_peers_info()
Returns the last roster received on the rendezvous of the world as a dictionary with keys peers, update_count and last_updated. It returns None on the public network and before the first roster. NodeConn.set_world_agents_and_world_masters_lists_from_rendezvous calls it.
defget_messages(self,kind:str="all")->tuple:"""Pops and decodes this instance's inbound batch (passthrough to the transport). P2P returns (chat_messages, session_inbounds): chat_messages are decoded, sender-verified Msg, session_inbounds are SessionInbound. The wire codec lives entirely in P2P (the manager stays protobuf-free); the Coordinator's chat path only gates membership and verifies the piggyback token on top of these. A transport without split pops (the browser one) serves kind "network" as "all" and "streams" with nothing. Args: kind: "all" (default), "network" (everything but the streams) or "streams" (one per stream channel). Returns: The tuple (chat_messages, session_inbounds). """ifkind=="all"ornotgetattr(self.p2p,"supports_split_pop",False):return([],[])ifkind=="streams"elseself.p2p.get_messages()returnself.p2p.get_messages(kind)
Pops the inbound frames of this network and returns (chat_messages, session_inbounds). The transport has already decoded the chat messages into Msg objects and checked their sender. The Session frames come as SessionInbound(peer_id, protocol_id, sess_msg). kind is "all" (default), "network" (everything but the streams) or "streams" (one message per stream channel). A transport without separate pops treats "network" as "all" and returns ([], []) for "streams". NodeConn.get_messages and NodeConn.drain_teardown call it.