unaiverse.custom¶
This module collects the defaults and the constants of the SDK in the class Custom and defines the two exception classes of the SDK. Custom is never instantiated: every value is a class attribute that the code reads as Custom.NAME at the moment it needs it. A program can therefore change a default by assigning the attribute before the code that reads it runs.
from unaiverse.custom import Custom
Custom.SAVE_STATS_EVERY = 60. # the world saves its statistics every minute
Custom.MAX_FILE_SIZE = 200 * 1024 * 1024 # refuse files larger than 200 MB
node = Node(world, node_name="Classroom") # reads the values above from here on
The time to assign a value depends on its reader.
- Most values are read at each use. An assignment takes effect from the next use.
- The send queues, the message limits and the file options reach the networking layer once at the start of the first
Nodeof the process. They must be assigned before creating the first node. SEND_STATS_EVERYandSAVE_CHECKPOINT_EVERYare overwritten by theNodeconstructor with its argumentssend_stats_everyandsave_checkpoint_every.- The values computed from other values (
SEND_TICKET_TIMEOUT,REASSEMBLY_MAX_BYTES_PER_PEER,HSM_TRANSIT_META_NAMES,RESERVED_*,DEFAULT_WILDCARDS,NOT_ALLOWED_STATE_NAMES,SYSTEM_INTERACTION_UUID) are computed once when the module is imported. Changing their sources later does not update them. - The environment variables are read once when the module is imported. They must be in the environment before the first
import unaiverse. A variable holding a non-integer where an integer is expected makes the import fail withValueError.
Custom
¶
The defaults and constants of UNaIVERSE as class attributes. The sections below list every attribute with its value, its unit, the code that reads it and the effect of the value.
Timers of the node¶
10. seconds. The node sends its dynamic profile (addresses, connections, role) to the UNaIVERSE server at most this often and only when its connections changed. A world also sends its pending badges in the same step. A Session that reconnects counts on this delay to find the new addresses of a peer that moved.
20. seconds. The timeout of each attempt of every HTTP request of the node to the UNaIVERSE server.
GET_NEW_TOKEN_EVERY
class-attribute
instance-attribute
¶
84600. seconds (23 hours and 30 minutes). The node asks the UNaIVERSE server for a new token this often. A failed request is retried after DEFAULT_TIMEOUT seconds.
10. seconds. A world publishes the list of its members (the rendezvous) to them at least this often. It publishes earlier when the list or a role changes.
150. seconds. The node tells the UNaIVERSE server that it is alive this often. The first answer also tells the node whether another process already runs the same node (see SKIP_WAS_ALIVE_CHECK).
10. seconds. The node of a world calls Stats.save_to_disk() this often.
30. seconds. An agent in a world sends its buffered statistics to the world this often. The Node constructor overwrites the value with its argument send_stats_every (default 30.).
-1. seconds. The node saves the state of the agent or world it hosts this often. A value of 0 or less disables the periodic save. The Node constructor overwrites the value with its argument save_checkpoint_every. With a positive value the node also saves once when it stops.
10.0 seconds. The node switches the clock to slow mode after this many seconds without network exchanges while no interaction is open. Statistics do not count as exchanges. The same condition also lengthens the pause of the network loop (see NETWORK_LOOP_INTERVAL_IDLE).
2.0 seconds. The minimum time between two cycles of the clock in slow mode. clock.run_slower() reads it.
30.0 seconds. The time that an agent waits before it tries again to join a world that disconnected it. When the world asks for a different delay, the agent uses that one. The Session layer relies on it to schedule a rejoin after the end of its own reconnection window.
90.0 seconds. A world reserves a place for an agent when it grants the admission. A reservation that the agent does not redeem within this time is removed. The value must exceed the worst duration of a join (about 35 seconds to connect plus two handshake stages of 15 seconds each).
0.01 seconds. The pause between two passes of the network loop of a running node when it is not idle. The network loop serves the Sessions, the messages and the connections independently of the clock that paces the behaviors.
0.1 seconds. The pause between two passes of the network loop when the node is idle under the condition of SLOW_DOWN_CLOCK_AFTER.
64 messages. Messages that change the hosted agent or world (interactions, statuses, roles) wait for the end of the running tick. This is the maximum number of such waiting messages per sender. Past it a new interaction is rejected and the sender receives a notice of the rejection. Any other message is logged and dropped.
DEFERRED_MSGS_MAX_BYTES
class-attribute
instance-attribute
¶
268435456 bytes (256 MB). The maximum size of all the messages from all senders that wait for the end of the tick. Exceeding it has the same effect as exceeding DEFERRED_MSGS_MAX_PER_PEER.
Send queues¶
A direct message to a peer goes to a queue of that peer and a writer of the networking layer sends it. A full queue refuses the new message (the send returns False) and keeps refusing until it has drained to the low-water mark. Messages already queued are never dropped one by one. The networking layer receives these values once at the start of the first node of the process.
64 messages. The capacity of the queue of each peer in messages.
SEND_QUEUE_MAX_BYTES_PER_PEER
class-attribute
instance-attribute
¶
1140850688 bytes (1 GB plus 64 MB). The capacity of the queue of each peer in bytes. It exceeds MAX_MESSAGE_SIZE so that one message of the maximum size fits.
SEND_QUEUE_MAX_BYTES_TOTAL
class-attribute
instance-attribute
¶
4294967296 bytes (4 GB). The capacity of all the queues together.
0.5. The fraction of its capacities to which a queue that refused a message must drain before it accepts new ones.
60. seconds. When the oldest unsent message of a queue has waited this long with no progress, the whole queue is dropped.
3. The queue of a peer is dropped after this number of failed writes in a row. Each write uses a new stream.
(1., 2., 4.) seconds. The wait before the first, second and third retry of a failed write. Further retries wait as long as the last entry.
10. seconds. The deadline of the write of a frame is this value plus the size of the frame divided by SEND_WRITE_MIN_BYTES_PER_SEC.
SEND_WRITE_MIN_BYTES_PER_SEC
class-attribute
instance-attribute
¶
1048576 bytes per second (1 MB/s). The slowest link that a write is allowed to wait for.
1024 events. The networking layer keeps at most this many send events (sent, failed, dropped) until the node reads them. The oldest events are discarded first.
5. seconds. The refusals of a full queue are logged at most once in this interval for each peer. The connection pool reads it at each refusal.
Large messages and files¶
A direct message larger than CHUNK_SIZE travels as a sequence of chunks to a peer that announced support for chunks. A peer without that support (older nodes and browsers) and every broadcast or Session payload keep the limit LEGACY_MAX_MESSAGE_SIZE of a single frame. The networking layer receives the values of this section at the start of the first node of the process.
5242880 bytes (5 MB). The size of the message data carried by one chunk. A value of 0 or less disables chunked messages.
1073741824 bytes (1 GB). The maximum size in memory of one sent or received message when chunks are available. A value of 0 means no limit. The node also publishes in its profile the limit that peers must respect when they send to it. That limit is this value when chunks are available and LEGACY_MAX_MESSAGE_SIZE otherwise.
LEGACY_MAX_MESSAGE_SIZE
class-attribute
instance-attribute
¶
52428800 bytes (50 MB). The maximum size of a message sent as a single frame. The networking module reads it when it is imported.
REASSEMBLY_MAX_BYTES_PER_PEER
class-attribute
instance-attribute
¶
REASSEMBLY_MAX_BYTES_PER_PEER = MAX_MESSAGE_SIZE
Equal to MAX_MESSAGE_SIZE at import. The maximum number of bytes under reassembly from one peer. A value of 0 means MAX_MESSAGE_SIZE.
REASSEMBLY_MAX_BYTES_TOTAL
class-attribute
instance-attribute
¶
4294967296 bytes (4 GB). The maximum number of bytes under reassembly from all peers together.
120. seconds. A message under reassembly whose next chunk does not arrive within this time is discarded.
True. Whether the node accepts file messages (files streamed from disk). Received files are saved under DOWNLOADS_DIR. The node announces the value in its profile and in the capabilities of its Sessions.
0 bytes. The maximum size of one file, sent or received. A value of 0 means no limit. The node announces the value in its profile.
None. The folder of the received files. None means the folder Downloads inside the application folder of the node (the folder that also holds its key). A path with ~ is expanded.
Environment variables¶
These attributes are read from the environment when unaiverse.custom is imported. A boolean variable is true when its value is the string 1.
The integer in NODE_PRINT, default 0. With 0 the log records the channels CRITICAL, ERROR and USER. With 1 or more it records every channel. LOG_CHANNELS takes precedence when it is not empty.
NODE_LOG, default false. Writes the log to a JSONL file in the folder of the running script.
LOG_APPEND
class-attribute
instance-attribute
¶
NODE_LOG_APPEND, default false. Appends to the existing log file across restarts instead of starting a new one.
LOG_CHANNELS
class-attribute
instance-attribute
¶
NODE_LOG_CHANNELS, default "". A comma-separated list of extra log channels to record (for example NETWORK,SESSION). Names are case-insensitive and unknown names are ignored. CRITICAL, ERROR and USER are always recorded.
PRINT_SCREEN_BASIC_ONLY
class-attribute
instance-attribute
¶
NODE_SCREEN_BASIC_PRINT, default false. Prints only CRITICAL, ERROR and USER on the screen while the other recorded channels still go to the file.
LOG_SINK_MODULE
class-attribute
instance-attribute
¶
NODE_LOG_SINK_MODULE, default "". The import path of a module with a function attach(log) that the node calls at start to observe the log. A failure to import or attach is logged and the node goes on.
SKIP_WAS_ALIVE_CHECK
class-attribute
instance-attribute
¶
NODE_IGNORE_ALIVE, default false. The node normally stops with GenException when the UNaIVERSE server reports that the same node is already running. True skips this check.
NODE_LIBP2PLOG, default false. Enables the internal log of the networking library of the node. Its lines go to the log channel P2P.
ENV_IS_ISOLATED
class-attribute
instance-attribute
¶
NODE_IS_ISOLATED, default false. Passed as the option is_isolated to both network endpoints of the node (the public one and the one of the world).
ENV_IS_PUBLIC
class-attribute
instance-attribute
¶
NODE_IS_PUBLIC, default false. Declares that the machine is reachable at a public address. Both endpoints then skip the discovery of their reachability.
ENV_IS_PUBLIC_RELAY
class-attribute
instance-attribute
¶
NODE_IS_PUBLIC_RELAY, default false. Makes the public endpoint of the node relay connections for other nodes. The world endpoint of a world node relays in any case.
ENV_USE_TLS
class-attribute
instance-attribute
¶
NODE_USE_TLS, default false. Enables secure connections with an automatic certificate on both endpoints. Custom certificates are given with the three variables below.
ENV_START_PORT
class-attribute
instance-attribute
¶
The integer in NODE_STARTING_PORT, default 0. The first port of the public endpoint. The world endpoint uses this port plus 4. With 0 both endpoints take random ports.
DOMAIN, default None. The domain name of a custom certificate. A custom certificate needs this variable, TLS_CERT_PATH and TLS_KEY_PATH together and raises ValueError when one of the three is missing.
TLS_CERT_PATH, default None. The path of the custom certificate in PEM format.
TLS_KEY_PATH, default None. The path of the private key of the custom certificate in PEM format.
PATH_TO_APPEND_ADDRESSES
class-attribute
instance-attribute
¶
NODE_SAVE_RUNNING_ADDRESSES, default None. An existing folder where the node appends its name and its public addresses to running.csv at start. A path that does not exist is ignored.
OFFLOAD_ENABLED
class-attribute
instance-attribute
¶
NODE_OFFLOAD, default true (any value other than 1 turns it off). The processor of an agent runs process and learn in a worker thread so that the node keeps running during a long forward or backward pass. In the browser runtime the processor always runs inline.
OFFLOAD_SLOW_S
class-attribute
instance-attribute
¶
The float in NODE_OFFLOAD_SLOW, default 0.5 seconds. In a multi-step interaction the processor runs inline so that each step takes its own sample. It moves to the worker thread when its last call took at least this long.
Behaviors¶
'<role>'. The wildcard of the role of a behavior. HybridStateMachine.set_role() fills it.
'<world>'. The wildcard of the peer id of the world. The node fills it when the agent joins.
'<agent>'. The wildcard of the peer id of the agent itself. The node fills it at start in the public behavior and when the agent joins a world in the world behavior.
'<partner>'. The wildcard of the public peer that got in touch last. The node and the agent fill it in the public behavior. The agent of a person never updates it by itself because the person chooses whom to write to.
DEFAULT_WILDCARDS
class-attribute
instance-attribute
¶
DEFAULT_WILDCARDS = {WORLD_WILDCARD: WORLD_WILDCARD, AGENT_WILDCARD: AGENT_WILDCARD, PARTNER_WILDCARD: PARTNER_WILDCARD, ROLE_WILDCARD: ROLE_WILDCARD}
{'<world>': '<world>', '<agent>': '<agent>', '<partner>': '<partner>', '<role>': '<role>'}. Every new HybridStateMachine adds these four wildcards mapped to themselves.
ACTION_TICKS_PER_STATUS
class-attribute
instance-attribute
¶
[" ✅ ", " 🔄 ", " ❌ "]. The marks logged after the message of an action for the codes 0, 1 and 2 when the behavior shows action ticks. The logger recognizes these strings to avoid repeating them.
'all'. The source state that stands for every state in transitions, teleports and add_transit() (see the JSON format).
NOT_ALLOWED_STATE_NAMES
class-attribute
instance-attribute
¶
NOT_ALLOWED_STATE_NAMES = {ALL_STATES_NAME}
{'all'}. Names refused for a state. Creating a State with one of them raises GenException.
Action arguments¶
Some argument names of actions have a meaning for the framework. The table summarizes the five classes and the attributes below define them.
| Class | Names | Where allowed |
|---|---|---|
| injected | interaction |
Only in the signature of the method. There it receives the Interaction that the call serves. Refused in the arguments of a behavior and of a request. |
| interaction fields | streams, num_steps, target, timeout, copy_sys, forced_uuid, id, volatile, data_samples, callback, num_samples_to_stream |
In the arguments of a behavior they configure the system interaction when the method does not declare them. In a request they must equal the matching field of the interaction. |
| timing of a transition | max_duration, retry_timeout, delay |
Only in the behavior. The action removes them from its arguments. Refused in the signature and in a request. |
| framework container | action_kwargs |
Only in the signature of send. |
| regular | any other name | Checked against the signature of the method. |
{'stream', 'streams'}. The @action decorator resolves the values of these arguments from stream names to net hashes on the network where the agent behaves.
AGENT_ARG_NAMES
class-attribute
instance-attribute
¶
{'agent', 'agents', 'partner', 'partners', 'targets', 'target'}. The @action decorator resolves the values of these arguments from node names to peer ids.
['max_duration']. The accepted names of the field that holds the maximum life of a transition. The first name is the one written by save().
['retry_timeout']. The accepted names of the field that holds the retry window of a transition.
['delay']. The accepted names of the field that holds the delay of a transition.
TIME_TO_WAIT_BEFORE_ACTING_ARG_NAMES
class-attribute
instance-attribute
¶
['time_to_wait_before_acting']. The accepted names of the field that holds the waiting time of a state.
INTERACTION_INJECT_NAMES
class-attribute
instance-attribute
¶
{'interaction'}. A parameter with this name receives the served Interaction and makes the transition request-only unless the behavior says "ready": true.
INTERACTION_FIELD_NAMES
class-attribute
instance-attribute
¶
INTERACTION_FIELD_NAMES = {'streams', 'num_steps', 'target', 'timeout', 'copy_sys', 'forced_uuid', 'id', 'volatile', 'data_samples', 'callback', 'num_samples_to_stream'}
{'streams', 'num_steps', 'target', 'timeout', 'copy_sys', 'forced_uuid', 'id', 'volatile', 'data_samples', 'callback', 'num_samples_to_stream'}. The fields of an Interaction that the arguments of a transition may set. Action moves them from its arguments to its system interaction unless the method declares them.
HSM_TRANSIT_META_NAMES
class-attribute
instance-attribute
¶
HSM_TRANSIT_META_NAMES = {SECONDS_ARG_NAMES[0], TIMEOUT_ARG_NAMES[0], DELAY_ARG_NAMES[0]}
{'max_duration', 'retry_timeout', 'delay'}. The timing names of a transition, built from the three lists above at import.
{'action_kwargs'}. A name reserved for the framework and refused everywhere except in the signature of the actions in SPECIAL_ACTION_NAMES.
{'send'}. Actions that may declare action_kwargs. Because they resolve their arguments themselves, the @action decorator leaves their arguments untouched.
RESERVED_IN_BODY_SIGNATURE
class-attribute
instance-attribute
¶
RESERVED_IN_BODY_SIGNATURE = HSM_TRANSIT_META_NAMES | WIRE_SENTINEL_NAMES
HSM_TRANSIT_META_NAMES | WIRE_SENTINEL_NAMES. The names reserved in the signature of a method. No code of the SDK reads this attribute in the current version.
RESERVED_IN_ACTION_KWARGS
class-attribute
instance-attribute
¶
RESERVED_IN_ACTION_KWARGS = HSM_TRANSIT_META_NAMES | WIRE_SENTINEL_NAMES | INTERACTION_INJECT_NAMES
HSM_TRANSIT_META_NAMES | WIRE_SENTINEL_NAMES | INTERACTION_INJECT_NAMES. The names that Action.same_as skips when it compares arguments and that the interactions refuse in their arguments.
10.0 seconds. The retry window given to a multi-step action without one and to the action that runs send(wait_completion=True). The node also uses it as the time limit of the alive and profile requests to the UNaIVERSE server. The action send_engage passes it as the timeout of its engagement requests.
Equal to DEFAULT_TIMEOUT at import (10.0 seconds). The default time that ticket.wait() of a tracked send waits for the outcome of the send.
Interactions¶
"sys". The id of the system interaction of an action. The action serves this interaction when it runs on the initiative of the agent.
"system". The requester and the target of a system interaction. Interaction.is_system() compares the requester with this value.
SYSTEM_INTERACTION_UUID
class-attribute
instance-attribute
¶
SYSTEM_INTERACTION_UUID = SYSTEM_INTERACTION_ID + '_' + SYSTEM_INTERACTION_LABEL
"sys_system". The uuid under which streams keep the data of the system interaction and to which the agent binds its standard streams.
100. The maximum number of interactions (sent, received and created by the agent itself) that the interaction manager of an agent tracks at the same time.
MAX_STREAM_DATA_WITHOUT_INTERACTIONS
class-attribute
instance-attribute
¶
10. A stream keeps at most this many data entries that belong to no interaction. The oldest ones are evicted first.
300. seconds. The maximum life of an interaction. The interaction manager closes an interaction older than this and streams drop the data of expired interactions. An interaction with a shorter timeout of its own lives less.
0. seconds. A completed interaction stays in the list of the recently completed ones for at least one clock cycle and this many seconds before it is drained. An interaction closed by a disconnection is drained at once.
"fake_system". No code of the SDK reads this attribute in the current version.
GenException
¶
Bases: Exception
The base exception of the SDK, a plain subclass of Exception with no extra attributes. The SDK raises it for configuration errors (a world folder without roles, a behavior with an invalid format, a reserved state name). Every call of log.critical() also raises it after logging the message. The node stops unless a caller catches it.
from unaiverse.custom import GenException
try:
world = World(world_folder="classroom/")
except GenException as e:
print(f"Invalid world: {e}")
RootServerError
¶
RootServerError(message: str, *, api: str, api_rejected: bool = False, state_code: str | None = None, state_message: str | None = None, data_code: str | None = None, data: dict | list | None = None, flags: dict | None = None, status: int | None = None)
Bases: GenException
Source code in unaiverse/custom.py
The subclass of GenException that reports the failure of a request to the UNaIVERSE server. The attribute api_rejected tells the two kinds of failure apart. With True the server answered and refused. Repeating the request cannot change the outcome. With False the request failed in transit and a retry may succeed. The node raises it from its requests to the server and stops retrying a refused request.
| Argument | Type | Default | Meaning |
|---|---|---|---|
message |
str |
required | The error message. |
api |
str |
required | The path of the API that was called (for example /account/node/cv/badge/assign). |
api_rejected |
bool |
False |
True for a refusal of the server and False for a failure in transit. |
state_code |
str \| None |
None |
The state code in the envelope of the answer. |
state_message |
str \| None |
None |
The state message in the envelope of the answer. |
data_code |
str \| None |
None |
The field data.code of the answer that distinguishes the kinds of refusal. |
data |
dict \| list \| None |
None |
The data of the refusal (for example the state of the acceptance of the legal terms). |
flags |
dict \| None |
None |
The flags of the answer. None becomes {}. |
status |
int \| None |
None |
The HTTP status code. |
Every argument except message is stored in the attribute with the same name.