This module holds Action and ActionInteractionList. An Action binds one method of an agent to a transition (or to a state) of a HybridStateMachine together with the arguments written in the behavior, the readiness flags, the three timing limits and the queue of the requests that other agents sent for it. ActionInteractionList is that queue. The machine creates both. add_transit() and add_state() build one Action per transition or state and request_action() appends to the queue of the matching action. A developer meets Action objects in custom policies and filters because both receive the list of feasible actions (see Policies). The concepts behind actions are in Actions and the requests are described in Interactions.
The methods that an Action wraps are the async methods of an agent marked with @action. The decorator lives in unaiverse.agent and fixes the contract that Action relies on.
The method is async and returns a truth value. Action treats every truthy value as success and every falsy value (False, 0, "", []) as failure.
A method that returns None is logged as an error and counts as False.
An exception raised by the method is logged with its traceback and counts as False. The machine and the node keep running.
Before the call the decorator resolves the arguments named agent, agents, partner, partners, target and targets from node names to peer ids and the arguments named stream and streams from stream names to net hashes (see Custom.AGENT_ARG_NAMES and Custom.STREAM_ARG_NAMES). The action send is excluded because it resolves its own arguments.
A parameter named interaction receives the Interaction that the call serves. Its presence also makes the transition request-only unless the behavior says "ready": true explicitly.
fromunaiverse.agentimportAgent,actionclassReferee(Agent):@actionasyncdefstart_match(self,players:int=2,interaction=None)->bool:iflen(self.world_agents)<players:returnFalse# the machine retries or moves on, depending on retry_timeoutreturnTrue
The machine awaits an action as await action(interaction) and receives one of four integer codes. Called without an argument, the action serves its own system interaction. This is how the machine runs an action on the initiative of the agent. An interaction is single-step when its num_steps is 1 or negative (the default -1 means no data stream) and multi-step when num_steps is greater than 1 or still a wildcard string. A multi-step interaction runs the method once per data sample. The call goes through these steps:
The arguments are built from three sources in decreasing priority: (1) the arguments of the transition, (2) the arguments of the interaction after the replacement of the wildcards and (3) the defaults of the method. A value written in the behavior therefore wins over the value of a request. A parameter missing from all three sources is logged and raises AssertionError.
At the first attempt the call prints the message of the action and records the starting time of the interaction. A pedantic single-step action also starts its retry timer at this point.
When the interaction has timed out, the call returns without running the method. The interaction times out when max_duration seconds have passed since its first attempt or retry_timeout seconds have passed since the last successful step. A single-step action returns 2. A multi-step action returns 0 when at least one step was done and 2 otherwise.
After its first step, a multi-step action returns 1 without running the method as long as one of its streams lacks fresh data.
The method runs with the parameter interaction filled when the method declares it.
A falsy result gives the codes of the first table below and a truthy result the codes of the second one.
Falsy result
Pedantic (retry_timeout > 0)
Not pedantic
single-step
1
2
multi-step, no step done yet
2
2
multi-step, at least one step done
1
0
Truthy result
Code
single-step
0
multi-step, last step done
0
multi-step, more steps to go
1
0 completes the transition, 1 keeps the machine on this action and 2 discards the attempt (see the codes in the machine). An interaction with num_steps equal to 0 is neither single-step nor multi-step and the call returns -1. A successful step restarts the retry timer and records the data tags that the step consumed. When a multi-step interaction without retry_timeout is bound to the action, the action receives Custom.DEFAULT_TIMEOUT (10 seconds) as retry window and becomes pedantic.
def__init__(self,name:str,args:dict,agent:"AgentBasics",idx:int=-1,ready:bool=True,msg:str|None=None,avoid_changing_ready:bool=False,teleport:bool=False,high_priority:bool=False,max_duration:float|str=0.,retry_timeout:float|str=0,delay:float|str=0):"""Initializes an `Action` object, which encapsulates a method to be executed on a given object (`agent`) with specified arguments. It sets up various properties for managing multistep actions, including `total_steps`, `total_time`, and `retry_timeout`. It also handles wildcard argument replacement and checks for existence of required parameters. It identifies if the action is a 'not ready' type (e.g., `do_`, `get_`) and sets its initial status accordingly. Args: name: The name of the method to call. args: A dictionary of arguments for the method. agent: The object on which the method will be executed. idx: A unique ID for the Custom. ready: A boolean indicating if the action is ready to be executed. msg: An optional human-readable message. avoid_changing_ready: A boolean indicating that the selected ready state should not be changed by internal rules. teleport: A boolean indicating that this action must be hidden when drawing the state machine ('teleport'). high_priority: A boolean indicating that this action must be preferred over others by the policy. max_duration: The number of seconds representing the max duration of this action (from when it starts). When <= 0., then no limits. It can be a wildcard (str). retry_timeout: The number of seconds representing the max time we keep try running this action before giving up. When <= 0., then no timeouts at all. It can be a wildcard (str). delay: The number of seconds that must pass when joining a state before considering this action. When <= 0., then no delays at all. It can be a wildcard (str). """# Basic propertiesself.name=name# Name of the action (name of the corresponding method)self.args=args.copy()# Dictionary of arguments to pass to the action (shallow copy, we will remove some)self.agent:"AgentBasics"=agent# Object on which the method whose name is self.name is searchedself.interactions:ActionInteractionList=ActionInteractionList()# List of interactionsself.id=idx# Unique ID of the action (-1 if not needed)self.msg=msg# Human-readable message associated to this instance of actionself.inner=readyself.outer=Trueself.state_machine=Noneself.teleport=teleportself.high_priority=high_priorityself.__mark=None# Who the message was last printed for (None: nobody), so that the retries of a failing action print it onceself.__msg_printed_for:str|None=None# Fix UNICODE charsifself.msgisnotNone:self.msg=html.unescape(self.msg)# Reference elementsassertself.agentisnotNoneself.__fcn=self.__action_name_to_callable(name)# The real method to be calledself.__sig=inspect.signature(self.__fcn)# Signature of the method for argument inspection# Parameter names and default valuesself.param_list=[]# Full list of the parameters that the action supportsself.param_to_default_value={}# From parameter to its default value, if anyself.__get_action_params()# This will fill the two attributes above# Time-based metricsself.__action_max_duration=max_duration# A total time <= 0 means "no total time at all"self.__action_max_duration_with_wildcard=max_durationifisinstance(max_duration,str)elseNoneself.__guess_total_time(self.args)# This will "guess" the value of self.__action_max_duration from args dict# Time-based metricsself.__action_retry_timeout=retry_timeout# A retry_timeout <= 0 means "no total time at all"self.__action_retry_timeout_with_wildcard=retry_timeoutifisinstance(retry_timeout,str)elseNoneself.__guess_timeout(self.args)# This will "guess" the value of self.__action_retry_timeout from the args dictself.__action_pedantic_by_default=(self.is_pedantic())ifnotisinstance(self.__action_retry_timeout,str)elseFalse# Time-based metricsself.__delay=delayself.__delay_with_wildcard=delayifisinstance(delay,str)elseNoneself.__guess_delay(self.args)# This will "guess" the value of self.__delay from the args dict# Checking arguments (also removing 'retry_timeout', 'delay', etc...)self.check_provided_args(self.args,exception=True,remove_special_arguments=True)# Argument values replaced by wildcards (commonly assumed to be in the format <value>)self.wildcards={}# Value-to-value (es: <playlist> to this:and:this)self.args_with_wildcards=copy.deepcopy(self.args)# Backup of the originally provided argumentsself.msg_with_wildcards=self.msg# Fixing (forcing NOT-ready on some actions)ifnotavoid_changing_ready:forpinself.param_list:ifpinCustom.INTERACTION_INJECT_NAMES:self.inner=Falseself.outer=Truebreak# Whether for this Action we've already register_lazy a system_interaction,# and whether `copy_sys` was requested for the current round.self._lazy_registered=Falseself._must_lazy_register=Falseself._copy_sys_on_register=False# Build the initial system_interaction (lightweight dummy or interaction-shaped). MUST stay# at the very end of __init__.self.__build_system_interaction()
The binding of one method of an agent to a transition or a state. The machine creates it.
Argument
Type
Default
Meaning
name
str
required
The name of the method. It is resolved on agent with getattr and a missing method raises AttributeError.
args
dict
required
The arguments written in the behavior. The object keeps a shallow copy.
agent
AgentBasics
required
The object that owns the method.
idx
int
-1
The numeric id of the action in the machine.
ready
bool
True
The inner readiness: whether the action can run on the initiative of the agent.
msg
str \| None
None
The message printed at the first attempt. HTML entities are decoded.
avoid_changing_ready
bool
False
With False an action whose method declares a parameter named interaction becomes request-only whatever ready says.
teleport
bool
False
Whether the action labels a teleport.
high_priority
bool
False
Whether the default policy prefers it.
max_duration
float \| str
0.
The maximum life in seconds since the first attempt. A value of 0 or less means no limit and a string is a wildcard.
retry_timeout
float \| str
0
The retry window in seconds since the last successful step. A value greater than 0 makes the action pedantic and a string is a wildcard.
delay
float \| str
0
The seconds after entering the source state before the action becomes feasible. A string is a wildcard.
The constructor processes the arguments in this order:
It inspects the signature of the method. A parameter named max_duration, retry_timeout or delay (or action_kwargs in any method other than send) raises GenException.
It reads max_duration, retry_timeout and delay from args when present. These values override the constructor arguments and are removed from args. A numeric value below 0 becomes 0 and a non-numeric string is kept as a wildcard.
It validates args with check_provided_args(exception=True). The keys interaction and action_kwargs raise ValueError like any key that is neither a parameter of the method nor an interaction field.
It makes the action request-only when the method declares interaction and avoid_changing_ready is False.
It builds the system interaction. Each key of args that is an interaction field (see Custom.INTERACTION_FIELD_NAMES) and not a parameter of the method moves from the arguments to the system interaction. The system interaction is registered with the interaction manager of the agent at the first call when it carries streams, data samples or num_steps greater than 0. When the field copy_sys is True, the registration also copies into each stream of the interaction the last sample stored under the UUID of the system interaction.
Attribute
Type
Meaning
name, id, agent, teleport, high_priority
The constructor arguments.
args
dict
The arguments of the behavior after the replacement of the wildcards. The timing keys and the interaction fields are not part of it.
args_with_wildcards
dict
A deep copy of the arguments as written in the behavior.
msg, msg_with_wildcards
str \| None
The message after and before the replacement of the wildcards.
inner
bool
The inner readiness (the JSON field ready).
outer
bool
Whether the action accepts requests from other agents. It starts True.
interactions
ActionInteractionList
The pending requests.
param_list
list[str]
The parameter names of the method in signature order.
param_to_default_value
dict
The default values of the parameters that have one.
system_interaction
Interaction
The interaction served when the action runs on the initiative of the agent.
wildcards
dict
The same dictionary object that holds the wildcards of the machine.
defis_ready(self,consider_interactions:bool=True,delay_starting_time:float=-1.)->bool:"""Checks if the action is ready to be executed. It returns `True` if the `ready` flag is set or if there are any pending interactions. Args: consider_interactions: A boolean flag to include pending interactions in the readiness check. delay_starting_time: The starting time from which the delay is calculated (in seconds). Returns: A boolean indicating the action's readiness. """is_delayed=(delay_starting_time>0andself.__delay>0and(time.perf_counter()-delay_starting_time)<=self.__delay)returnnotis_delayedand(self.inneror(consider_interactionsandself.outerandlen(self.interactions.get_interactions(doable_only=True))>0))
Returns True when the action can run now. A delayed action is never ready. The action is delayed when delay_starting_time is positive and no more than delay seconds have passed since then. Outside the delay the action is ready when inner is True or when consider_interactions is True, outer is True and at least one pending interaction can be served now. An interaction can be served when it is not completed, its requester is a known agent and all its streams have fresh data. The machine passes the starting time of the current state as delay_starting_time.
defset_as_ready(self)->None:"""Sets the action's ready flag to `True`, indicating it can now be executed."""self.outer=False# For the moment, I prefer to avoid "solid" actions to also take requests from the outsideself.inner=True
Makes the action ready on its own (inner=True) and stops it from accepting new requests (outer=False). Returns None.
defset_as_not_ready(self)->None:"""Sets the action's ready flag to `False`, preventing it from being executed (unless requested from the outside)."""self.inner=Falseself.outer=True
Makes the action request-only (inner=False, outer=True). HybridStateMachine.wait_for_all_actions_that_start_with() and wait_for_all_actions_that_include_an_arg() call it. Returns None.
defget_total_time(self)->float|str:"""Returns the total execution time configured for this action (0 means no limit)."""returnself.__action_max_duration
Returns max_duration in seconds. A value of 0 or less means no limit and a string is a wildcard not yet replaced.
defget_timeout(self)->float|str:"""Returns the retry_timeout configured for this action (0 means no retry_timeout)."""returnself.__action_retry_timeout
Returns retry_timeout in seconds. A value of 0 or less means no retry window and a string is a wildcard not yet replaced.
defget_delay(self)->float|str:"""Returns the delay configured for this action (0 means no delay)."""returnself.__delay
Returns delay in seconds. A value of 0 means no delay and a string is a wildcard not yet replaced. A delay that is still a string when the machine evaluates the transition raises TypeError.
defis_pedantic(self)->bool:"""Checks if a retry_timeout has been configured for the Custom. Returns: A boolean indicating if a retry_timeout is set. """returnself.__action_retry_timeout>0
Returns True when retry_timeout is greater than 0. A pedantic action that fails returns code 1 and the machine keeps trying the same transition until the action succeeds or its retry window ends.
defis_pedantic_by_default(self)->bool:"""Checks if an action was pedantic at construction time. Returns: A boolean indicating if the action was pedantic since when it was generated. """returnself.__action_pedantic_by_default
Returns whether the action was pedantic when it was built (or when its retry_timeout wildcard was replaced). send(wait_completion=True) and stepwise() read it to restore the original behavior after they made the action pedantic for a while.
defset_timeout(self,retry_timeout:float)->None:"""Sets the retry_timeout to a custom value."""self.__action_retry_timeout=retry_timeoutifretry_timeout>0.:self.__action_pedantic_by_default=False
Replaces the retry window of the action with the argument retry_timeout. A positive value also marks the action as not pedantic by default. send() and stepwise() call it with a positive value to make the action wait and with -1. to clear the window again. Returns None.
defset_default_timeout(self)->None:"""Sets the retry_timeout to the class-level default value (``Custom.DEFAULT_TIMEOUT``)."""ifnotself.is_pedantic():self.__action_retry_timeout=Custom.DEFAULT_TIMEOUT
Gives a non-pedantic action the retry window Custom.DEFAULT_TIMEOUT (10 seconds). A pedantic action keeps its own window. send(wait_completion=True) calls it and so does the binding of a multi-step interaction without a retry window to the action. Returns None.
defadd_interaction(self,interaction:Interaction)->bool:"""Adds a new interaction to the action's internal list. This is used to track pending requests that might make the action ready to be executed. Args: interaction: Interaction object. """# Let's augment interaction objectifnotself.allows_outer_interactions():returnFalseinteraction.set_action_ref(self)self.interactions.add(interaction)returnTrue
Appends interaction to the queue of pending requests and links it to this action. The link validates the arguments of the request and gives a multi-step interaction the default retry window when the action has none. Returns False without queuing when the action does not accept requests (outer is False) and True otherwise. A request whose arguments the action does not accept raises ValueError. HybridStateMachine.request_action() calls it.
defget_list_of_interactions(self)->'ActionInteractionList':"""Retrieves the list of pending interactions (ActionInteractionList object). Returns: The list of pending interactions, i.e., an object of type ActionInteractionList. """returnself.interactions
Returns the ActionInteractionList of the pending requests. The object is not a copy.
defclear_interactions(self,requester:str|None=None)->None:"""Clears all pending requests from the action's list."""ifrequesterisNone:self.interactions=ActionInteractionList()else:ifself.interactions.is_requester_known(requester):requests=self.interactions.get_interactions(requester)assertisinstance(requests,list)forreqinrequests:self.interactions.remove(req)
Without arguments the method replaces the queue with an empty one. With requester it removes only the requests of that peer. Returns None.
defclear_interaction(self,requester:str,req_id:int)->None:"""Removes a single specific interaction identified by requester and insertion-order ID. Args: requester: The peer ID of the requester who owns the interaction. req_id: The insertion-order ID of the interaction to remove. """req=self.interactions.get_interaction(req_id,requester)ifreqisnotNone:self.interactions.remove(req)
Removes the request at position req_id in the sub-list of requester. Nothing happens when that position is empty. Returns None.
defsame_as(self,name:str,args:dict|None)->bool:"""Compares the current action to a target action by name and arguments. It returns `True` if they are considered the same, ignoring specific arguments like time or retry_timeout. Args: name: The name of the target Custom. args: The arguments of the target Custom. Returns: A boolean indicating if the actions are a match. """ifargsisNone:args={}# The current action is the same of another action called with some arguments "args" if:# 1) it has the same name of the other action# 2) the name of the arguments in "args" are known and valid# 3) the values of the arguments in "args" matches the ones of the current action, being them default or not# the values of those arguments that are not in "args" are assumed to the equivalent to the ones in the current# action, so:# - if the current action is act(a=3, b=4), then it is the same_as(name='act', args={'a': 3})# - if the current action is act(a=3, b=4), then it is the same_as(name='act', args={'a': 3, 'b': 4, 'c': 5})args_to_exclude=Custom.RESERVED_IN_ACTION_KWARGSreturn(name==self.nameandself.check_provided_args(args)andall(kinargs_to_excludeorknotinself.argsorself.args[k]==vfork,vinargs.items()))
Returns True when a call of name with args matches this action. Three conditions must hold: (1) name equals the name of the action, (2) check_provided_args(args) accepts the keys and (3) every key of args that the action also fixes has the same value. The keys max_duration, retry_timeout, delay, action_kwargs and interaction are not compared. Keys absent from args are not compared either. For an action act(a=3, b=4) the calls same_as("act", {"a": 3}) and same_as("act", {}) return True and same_as("act", {"a": 5}) returns False. The machine uses it to route requests and to refuse duplicated transitions.
defcheck_provided_args(self,args:dict,exception:bool=False,remove_special_arguments:bool=False)->bool:"""A helper method that validates that all provided arguments for an action exist in the action's parameter list. It can either raise a `ValueError` or return a boolean. Args: args: The dictionary of arguments to check. exception: If `True`, a `ValueError` is raised on failure. remove_special_arguments: If `True`, removes from the args dictionary those special arguments that are internally handled in a specific manner (such as time-related arguments). Returns: True if all arguments are valid, False otherwise (if `exception` is `False`). """ifargsisnotNone:forkinlist(args.keys()):ifkinCustom.HSM_TRANSIT_META_NAMES:ifremove_special_arguments:delargs[k]elifexception:raiseValueError(f"Parameter {k} is not a valid param for action"f" {self.name} (it is a private HSM transit meta name)")else:returnFalseelifkinCustom.WIRE_SENTINEL_NAMESorkinCustom.INTERACTION_INJECT_NAMES:ifexception:raiseValueError(f"Parameter {k} is not a valid param for action"f" {self.name} (it is reserved)")else:returnFalseelifkinCustom.INTERACTION_FIELD_NAMES:continue# Skippingelifknotinself.param_list:ifexception:raiseValueError(f"Parameter {k} is not a valid param for action"f" {self.name} (it is not part of the action signature)")else:returnFalsereturnTrue
Validates the keys of args against the action and returns True when they are all acceptable. The method skips the interaction fields and refuses (1) the timing keys max_duration, retry_timeout and delay, (2) the reserved names action_kwargs and interaction and (3) any name outside the signature of the method. With remove_special_arguments=True the timing keys are deleted from args in place instead of being refused. With exception=True a refused key raises ValueError and with exception=False the method returns False.
defget_actual_params(self,additional_args:dict|None)->dict|None:"""A helper method that resolves all parameters for an action's execution. It combines the action's default arguments, initial arguments, and any additional arguments provided during the call, ensuring all necessary parameters have a value. Args: additional_args: A dictionary of arguments to be combined with the action's defaults. Returns: A dictionary of all resolved arguments, or `None` if a required parameter is missing. """actual_params={}params=self.param_listdefaults=self.param_to_default_valueforparam_nameinparams:ifparam_nameinself.args:actual_params[param_name]=self.args[param_name]elifadditional_argsisnotNoneandparam_nameinadditional_args:actual_params[param_name]=additional_args[param_name]elifparam_nameindefaults:actual_params[param_name]=defaults[param_name]else:log.error(f"Getting actual params for {self.name}; missing param: {param_name}")returnNonereturnactual_params
Returns the keyword arguments of the next call as a dictionary with one entry per parameter of the method. Each value comes from the arguments of the action, then from additional_args, then from the default of the parameter. A parameter without a value in any of the three sources is logged as an error and makes the method return None.
defset_wildcards(self,wildcards:dict[str,str|float|int|list[str]]|None)->None:"""Replaces wildcard values with new ones. Args: wildcards: A dictionary mapping wildcard placeholders to their concrete values. """self.wildcards=wildcardsifwildcardsisnotNoneelse{}
Replaces the dictionary of wildcards with wildcards (an empty one for None). Returns None.
defapply_wildcards(self)->None:"""Given the current wildcards, it applies the replacements they suggest to whatever uses them."""# Setting up the original wildcard-based arguments and messagesifself.args_with_wildcardsisNone:self.args_with_wildcards=copy.deepcopy(self.args)# Backup before applying wildcards (1st time only)else:self.args=copy.deepcopy(self.args_with_wildcards)# Restore a backup before applying wildcardsifself.msg_with_wildcardsisnotNone:self.msg=self.msg_with_wildcards# Applying wildcard-suggested replacements to argumentsself.__apply_wildcards_to_args(self.args)# Applying wildcard-suggested replacements to message and other stuffforwildcard_from,wildcard_toinself.wildcards.items():# ... to messageifself.msgisnotNone:self.msg=self.msg.replace(wildcard_from,str(wildcard_to))# ... to the restif(self.__action_max_duration_with_wildcardisnotNoneandwildcard_frominself.__action_max_duration_with_wildcard):self.__action_max_duration=(float(self.__action_max_duration_with_wildcard.replace(wildcard_from,str(wildcard_to))))if(self.__action_retry_timeout_with_wildcardisnotNoneandwildcard_frominself.__action_retry_timeout_with_wildcard):self.__action_retry_timeout=(float(self.__action_retry_timeout_with_wildcard.replace(wildcard_from,str(wildcard_to))))self.__action_pedantic_by_default=self.is_pedantic()ifself.__delay_with_wildcardisnotNoneandwildcard_frominself.__delay_with_wildcard:self.__delay=float(self.__delay_with_wildcard.replace(wildcard_from,str(wildcard_to)))# Now that wildcards have been resolved in self.args, rebuild the system_interaction so any# streams / num_steps / etc. reflect the concrete (post-wildcard) values.self.__build_system_interaction()
Rebuilds args and msg from the copies written in the behavior, replaces the wildcards in them and converts the timing fields that held a wildcard with float(). The rules are those of Wildcards. A replaced retry_timeout also updates the pedantic default. The method then rebuilds the system interaction from the resolved arguments. Returns None.
defset_msg(self,msg:str|None)->None:"""Sets the message associated to this Custom."""ifmsgisnotNone:self.msg=html.unescape(msg)self.msg_with_wildcards=self.msgelse:self.msg=Noneself.msg_with_wildcards=None
Replaces the message with msg after decoding its HTML entities. Both msg and msg_with_wildcards take the new value and None removes the message. Returns None.
defreset_msg_printing(self)->None:"""Lets the message of the action be printed again at its next attempt (the action completed, or the state machine left the state the action starts from)."""self.__msg_printed_for=None
Lets the message be printed again at the next attempt. The machine calls it when the action completes and when the machine leaves the source state. The message of a failing action is otherwise printed once per series of retries. Returns None.
defset_state_machine(self,hsm:"HybridStateMachine")->None:"""Registers the parent state machine that owns this action."""self.state_machine=hsmself.set_wildcards(hsm.get_wildcards())
Links the action to the machine hsm and gives it the wildcards of hsm. Returns None.
defto_dict(self)->dict:"""Converts the action's properties into a dict for easy serialization. Returns: A dict containing the action's properties. """return{"action":self.name,"action_kwargs":self.args,"msg":self.msg.encode("ascii","xmlcharrefreplace").decode("ascii")ifself.msgisnotNoneelseNone,"ready":self.inner,"high_priority":self.is_high_priority,Custom.SECONDS_ARG_NAMES[0]:self.__action_max_duration,Custom.TIMEOUT_ARG_NAMES[0]:self.__action_retry_timeout,Custom.DELAY_ARG_NAMES[0]:self.__delay}
Returns the field on of the JSON format: action, action_kwargs, msg (ASCII with HTML entities), ready, high_priority, max_duration, retry_timeout and delay. The arguments and the timing values are those after the replacement of the wildcards.
defto_list(self)->list:"""Converts the action's properties into a list for easy serialization and comparisons. Returns: A list containing the action's properties. """total_time=0.retry_timeout=0.delay=0.ifisinstance(self.__action_max_duration,str)orself.__action_max_duration>0:total_time=self.__action_max_durationifisinstance(self.__action_retry_timeout,str)orself.__action_retry_timeout>0.:retry_timeout=self.__action_retry_timeoutifisinstance(self.__delay,str)orself.__delay>0.:delay=self.__delayreturn[self.name,self.args,self.inner,self.outer,total_time,retry_timeout,delay,self.msg]
Returns [name, args, inner, outer, max_duration, retry_timeout, delay, msg] with the timing values clamped to 0. when they are not positive. HybridStateMachine.to_dict() compares these lists to find identical teleports.
defto_code_str(self)->str:"""Returns a compact code-style string representation of the action (for logging/debugging)."""s=f"aai:{self.name}|{self.args}|"iflen(self.interactions)>0:returns+"\n"+"\n".join(f" {inter.to_code_str(True)}"forinterinself.interactions)else:returns+"no-int"
Returns a compact string for the logs of the form aai:name|args| followed by one line per pending interaction or by no-int when there is none.
def__init__(self,max_per_requester:int=-1):"""Initializes an empty interaction list with an optional per-requester cap. Args: max_per_requester: Maximum number of interactions stored per requester (-1 for unlimited). """self.by_insertion_order=[]self.by_requester_and_by_insertion_order={}self.max_per_requester=max_per_requesterself.by_insertion_order_entering_time=[]
The queue of the pending requests of one action. It keeps the interactions in a global insertion order and in a separate insertion order for each requester. Each interaction stores its positions in the two orders (by_insertion_order_id and by_requester_insertion_order_id) and -1 once it leaves the queue. The object supports len() and iteration in global insertion order.
Argument
Type
Default
Meaning
max_per_requester
int
-1
The maximum number of interactions per requester. A new interaction beyond the limit evicts the oldest one of the same requester. A value of 0 or less means no limit.
Attribute
Type
Meaning
by_insertion_order
list[Interaction]
The interactions in global insertion order.
by_requester_and_by_insertion_order
dict[str, list[Interaction]]
The interactions of each requester in insertion order.
by_insertion_order_entering_time
list[float]
The time.perf_counter() value at which each interaction entered the queue.
defadd(self,interaction:Interaction)->None:"""Appends an interaction to the list, updating all internal indices. Interactions with ``uuid=None`` are deduplicated per requester. If ``max_per_requester`` is set, the oldest entry for that requester is evicted. Args: interaction: The Interaction object to add. """# Searching for already existing interactions with this UUID, FROM THE SAME REQUESTER# If already there - do not accumulate multiple requests with same UUID (useful also for system interactions)assertinteraction.requesterisnotNoneexisting_request_same_uuid=self.get_interaction_by_uuid(interaction.requester,interaction.uuid)ifexisting_request_same_uuid:# We skip this request if we are already taking care (running) of another one with the same UUIDifexisting_request_same_uuid.running:# This means the HSM is taking care of it, don't mess up things!log.error(f"Tried to add an interaction with the UUID of an already existing one that was in "f"'running' state, skipping (requester: {interaction.requester}")return# Since we know the requester is the same, we just "refresh" the existing interaction object,# without altering its position in the listself.by_insertion_order[existing_request_same_uuid.by_insertion_order_id]=interactioninteraction.by_insertion_order_id=existing_request_same_uuid.by_insertion_order_idself.by_requester_and_by_insertion_order[interaction.requester][existing_request_same_uuid.by_requester_insertion_order_id]=(interaction)interaction.by_requester_insertion_order_id=existing_request_same_uuid.by_requester_insertion_order_idreturn# We stop here in this case, no need to do any other things# Updating by-requester indexifinteraction.requesternotinself.by_requester_and_by_insertion_order:self.by_requester_and_by_insertion_order[interaction.requester]=[]if0<self.max_per_requester<=len(self.by_requester_and_by_insertion_order[interaction.requester]):inter=self.get_oldest_interaction(interaction.requester)ifinterisnotNone:self.remove(inter)else:log.critical("Unexpected behavior: getting the oldest interaction of a known requester returned None")by_requester_insertion_order_id=len(self.by_requester_and_by_insertion_order[interaction.requester])self.by_requester_and_by_insertion_order[interaction.requester].append(interaction)# Updating direct global indexinsertion_order_id=len(self.by_insertion_order)self.by_insertion_order.append(interaction)# Updating reverse indicesinteraction.by_insertion_order_id=insertion_order_idinteraction.by_requester_insertion_order_id=by_requester_insertion_order_id# Saving joining timeself.by_insertion_order_entering_time.append(time.perf_counter())
Appends interaction to the queue. An interaction with the same requester and the same uuid as a queued one replaces it in the same position. When the queued one is already running, the new one is logged as an error and dropped. The requester of the interaction must not be None (AssertionError). Returns None.
defremove(self,interaction:Interaction)->None:"""Removes an interaction from the list, reindexing all subsequent entries to keep indices consistent. Args: interaction: The Interaction object to remove. """ifinteraction.is_valid():if(interaction.by_insertion_order_id<len(self.by_insertion_order)andself.by_insertion_order[interaction.by_insertion_order_id]==interaction):foriinrange(interaction.by_insertion_order_id+1,len(self.by_insertion_order)):self.by_insertion_order[i].by_insertion_order_id-=1delself.by_insertion_order[interaction.by_insertion_order_id]delself.by_insertion_order_entering_time[interaction.by_insertion_order_id]d=self.by_requester_and_by_insertion_order[interaction.requester]foriinrange(interaction.by_requester_insertion_order_id+1,len(d)):d[i].by_requester_insertion_order_id-=1deld[interaction.by_requester_insertion_order_id]iflen(d)==0:delself.by_requester_and_by_insertion_order[interaction.requester]interaction.by_insertion_order_id=-1interaction.by_requester_insertion_order_id=-1
Removes interaction from both orders, shifts the positions of the interactions after it and marks its positions as -1. An interaction that is not in the queue is ignored. Returns None.
defremove_due_to_timeout(self,timeout_secs:float)->None:"""Removes all interactions that have been waiting longer than the specified retry_timeout. Args: timeout_secs: The maximum age in seconds; older interactions are removed. """to_remove=[]fori,reqinenumerate(self.by_insertion_order):if(time.perf_counter()-self.by_insertion_order_entering_time[i])>=timeout_secs:to_remove.append(req)forreqinto_remove:self.remove(req)
Removes every interaction that entered the queue at least timeout_secs seconds ago. Returns None.
defremove_completed(self)->None:"""Removes all interactions that have been marked as completed."""to_remove=[]fori,reqinenumerate(self.by_insertion_order):ifreq.completed:to_remove.append(req)forreqinto_remove:self.remove(req)
Removes every interaction whose completed flag is True. Returns None.
defmove_interaction_to_back(self,interaction:Interaction)->None:"""Moves an interaction to the back of the insertion-order list, preserving its original entering time. Args: interaction: The Interaction object to reposition. """iflen(self.by_insertion_order)>1andinteraction.is_valid():try:entering_time=self.by_insertion_order_entering_time[interaction.by_insertion_order_id]self.remove(interaction)self.add(interaction)self.by_insertion_order_entering_time[interaction.by_insertion_order_id]=entering_timeexceptExceptionase:raisee
Moves interaction to the end of both orders and keeps its original entering time. The machine calls it after a discarded attempt (code 2) to avoid serving the same request forever. Returns None.
defmove_requester_to_back(self,requester:str)->None:"""Moves all interactions belonging to a requester to the back of the list, preserving their entering times. Args: requester: The peer ID whose interactions should be moved to the back. """requests=self.get_interactions(requester)ifrequestsisnotNoneandisinstance(requests,list)andlen(requests)>0:requests_copy=[]entering_times=[]forreqinrequests:ifreq.is_valid():requests_copy.append(req)entering_times.append(self.by_insertion_order_entering_time[req.by_insertion_order_id])self.remove(req)fori,reqinenumerate(requests_copy):self.add(req)self.by_insertion_order_entering_time[req.by_insertion_order_id]=entering_times[i]
Moves every interaction of requester to the end of the global order and keeps their entering times. Returns None.
defget_interaction(self,req_order_id:int,requester:str|None=None)->Interaction|None:"""Retrieves an interaction by its insertion-order index, optionally scoped to a specific requester. Args: req_order_id: The insertion-order index of the interaction to retrieve. requester: If provided, scopes the lookup to the sub-list of this requester. Returns: The matching Interaction, or None if not found. """ifreq_order_id<0andreq_order_id!=-1:returnNoneifrequesterisNone:returnself.by_insertion_order[req_order_id]ifreq_order_id<len(self.by_insertion_order)elseNoneelse:ifrequesternotinself.by_requester_and_by_insertion_order:returnNonereturnself.by_requester_and_by_insertion_order[requester][req_order_id] \
ifreq_order_id<len(self.by_requester_and_by_insertion_order[requester])elseNone
Returns the interaction at position req_order_id in the global order (in the order of requester when given). The position -1 means the last one and any other negative position returns None. A position past the end returns None. The position -1 on an empty queue raises IndexError.
defget_oldest_interaction(self,requester:str|None=None,ignore_completed:bool=False) \
->Interaction|None:"""Returns the oldest (first-added) interaction, optionally scoped to a specific requester. Args: requester: If provided, scopes the lookup to the sub-list of this requester. ignore_completed: If True, completed interactions will be ignored/skipped. Returns: The oldest Interaction, or None if the list is empty. """ifnotignore_completed:returnself.get_interaction(0,requester)else:req=self.get_interaction(0,requester)i=1ifreqisnotNone:whilereq.completed:ifi<len(self):req=self.get_interaction(i,requester)i+=1else:returnNonereturnreq
Returns the first interaction of the global order (or of requester) and None for an empty queue. With ignore_completed=True the method skips completed interactions and returns None when all are completed. With both requester and ignore_completed=True the scan uses the length of the whole queue as its bound and can raise AttributeError when the requester has fewer interactions.
defget_most_recent_interaction(self,requester:str|None=None,ignore_completed:bool=False) \
->Interaction|None:"""Returns the most recently added interaction, optionally scoped to a specific requester. Args: requester: If provided, scopes the lookup to the sub-list of this requester. ignore_completed: If True, completed interactions will be ignored/skipped. Returns: The most recent Interaction, or None if the list is empty. """ifnotignore_completed:returnself.get_interaction(-1,requester)else:req=self.get_interaction(-1,requester)i=len(self)-2ifreqisnotNone:whilereq.completed:ifi>=0:req=self.get_interaction(i,requester)i-=1else:returnNonereturnreq
Returns the last interaction of the global order (or of requester). With ignore_completed=True the method scans backwards past completed interactions. An empty queue raises IndexError because the lookup uses the position -1.
defget_interaction_by_uuid(self,requester:str,uuid:str|None)->Interaction|None:"""Finds the first interaction for a given requester that matches the specified UUID. Args: requester: The peer ID of the requester. uuid: The UUID to search for (None is a valid UUID). Returns: The matching Interaction, or None if not found. """requests=self.get_interactions(requester)ifrequestsisNoneorlen(requests)==0:returnNoneassertisinstance(requests,list)forreqinrequests:ifreq.uuid==uuid:returnreqreturnNone
Returns the first interaction of requester whose uuid equals uuid (None is a valid uuid) or None when there is no match.
defkeep_only_the_most_recent_interaction(self,ignore_completed:bool=False)->None:"""Discards all interactions except the most recently added one, preserving its entering time. Args: ignore_completed: If True, completed interactions will be ignored/skipped. Returns: None """req=self.get_most_recent_interaction(ignore_completed=ignore_completed)ifreqisnotNone:entering_time=self.by_insertion_order_entering_time[req.by_insertion_order_id]self.clear()self.add(req)self.by_insertion_order_entering_time[req.by_insertion_order_id]=entering_timeelse:self.clear()
Empties the queue except for the most recent interaction (the most recent one not completed with ignore_completed=True) and keeps the entering time of that interaction. An empty queue raises IndexError. Returns None.
defget_interactions(self,requester:str|None=None,to_str:bool=False,doable_only:bool=False)->list[Interaction]|str:"""Returns interactions, optionally filtered by requester or "do-ability", or as a JSON string. Args: requester: If provided, returns only interactions from this requester. to_str: If True, returns a JSON-encoded string instead of a list. doable_only: If True, filters to only interactions that pass ``check_if_doable()``. Returns: A list of Interaction objects, or a JSON-encoded string if ``to_str`` is True. """ifrequesterisNone:reqs=self.by_insertion_orderifdoable_only:reqs=[reqforreqinreqsifreq.check_if_doable()]# This excludes completed tooifnotto_str:returnreqselse:returnjson.dumps([req.to_str()forreqinreqs])else:ifrequesterinself.by_requester_and_by_insertion_order:reqs=self.by_requester_and_by_insertion_order[requester]ifdoable_only:reqs=[reqforreqinreqsifreq.check_if_doable()]ifnotto_str:returnreqselse:returnjson.dumps([req.to_str()forreqinreqs])else:ifnotto_str:return[]else:returnjson.dumps([])
Returns the list of the queued interactions, all of them or those of requester alone. Without any filter the method returns the internal list and not a copy. doable_only=True keeps the interactions that can be served now (not completed, known requester, fresh data on every stream). to_str=True returns a JSON string with the to_str() of each interaction instead of the list. An unknown requester gives an empty list.
defclear(self)->None:"""Removes all interactions and resets all internal indices."""self.by_insertion_order.clear()self.by_requester_and_by_insertion_order.clear()self.by_insertion_order_entering_time.clear()
Empties the queue and its indices. The positions stored in the removed interactions are not reset. Returns None.
defis_requester_known(self,requester:str)->bool:"""Checks whether any interactions from the given requester are currently stored. Args: requester: The peer ID to look up. Returns: True if the requester has at least one interaction in the list, False otherwise. """returnrequesterinself.by_requester_and_by_insertion_order
Returns True when the queue holds at least one interaction of requester.