12 · Patterns, pitfalls and checklist¶
The machinery of a world is small: roles, behaviors, actions and one send. Most problems come from the way these pieces meet. A request reaches a state where its action does not exist, an action returns nothing, a callback assumes that every target has finished. This chapter collects the patterns that the example worlds repeat, the mistakes that are easy to make and a check that you can run before any node starts.
Patterns¶
Announce, act, collect, conclude. Every activity of the classroom has four transitions. A notice tells the members what is coming (give_next_lecture). A send starts the work (teach). A loop collects what comes back (on_data). A final action waits for the callback and draws the conclusions (evaluate_results). A waiting time on the state after the notice gives people time to read it.
Flags set by callbacks. A callback runs once when the last target has finished. It turns on a flag of the role only when interaction.is_completed() is True. An action of the behavior returns False until that flag is on. The behavior stays readable and the callback stays short.
A loop that ends by itself. A self-transition whose action returns True while something moves (on_data, collect) keeps the machine in the state as long as there is work. When the action returns False, the next transition of the state takes over. A grace period after the last movement lets late answers arrive.
Recovery as teleports. The reaction to a lost connection is the same from every state. A teleport to a recovery state with a delayed way back (wait_to_recover, 60 seconds, then init) keeps the main flow free of error handling.
Local resources in accept_new_role. Files, devices, credentials and data folders belong to the machine of the member. The role class opens them in accept_new_role and reads their location from the environment, never from the code that the world ships.
Interactive messages added at the edge. The classroom rewrites a class name into a form inside hook_before_sending_sample right before the sample leaves the node. Neither the behavior nor the models change to let people take part.
Pitfalls¶
An action that returns nothing. An action must return True or False. A missing return makes the action return None and the node logs this as a critical error. Check every branch.
A requested action in the wrong place. A request names an action and a source state (from_state). The target queues the request on the transition that leaves that state with that action. When from_state is missing, the target uses its current state. A request whose action has no transition out of that state is dropped with an error in the log of the target and nothing travels back. The interaction of the sender then ends only with its timeout. Pass from_state and make sure that the state of the target has the action.
Arguments that do not match. A request matches a transition only when its action_kwargs agree with the arguments fixed in that transition. A transition with args={} accepts any value. A transition that fixes an argument, on the other hand, accepts only requests with the same value.
A parameter named interaction. It turns the action into a requested one when the transition is created in Python (chapter 5). An action that should also run on its own initiative either omits this parameter or uses a JSON transition with an explicit "ready": true.
A callback that assumes success. The callback runs for every outcome, including TIMEOUT, REJECTED and DISCONNECTED. Check interaction.is_completed() before concluding and interaction.completion_reason before trusting an answer.
A fixed list of members. Members come and go. Ask get_agents_by_role at the moment you send. The targets that send really reached are in self.get_last_sent_interaction().target.
Blocking the node. All actions of a node run on the main asyncio task that also serves its sessions. A long computation inside an action delays the keep-alive answers. Slice it with stepwise (chapter 5) or move it into the processor. During process and learn the processor runs in a worker thread and leaves the main task free.
Code that cannot travel. Role files and their imports run on the machines of the members after analyze_code checks them. Imports of subprocess, ctypes, pty, socket, pickle, marshal or importlib are refused. So are calls to eval, exec, compile, __import__ and input, process execution and deletion of files through os or shutil. Keep such code in world.py or in files that the roles do not import.
Relative imports in stats.py. The joining node executes stats.py as a standalone module and relative imports cannot be resolved there.
Editing a running world. The world packs its code at startup. Changes in the world folder reach the members only after a restart of the world node and a new join of each member.
Roles without code. Every JSON file needs a Python file with the same name unless the folder has a single agent.py. Otherwise the world refuses to start. A role class that declares its own CUSTOM_ROLES must list the same roles as the JSON files.
Names that belong to another account. A bare node name refers to a node of your own account. Use "owner/node" for a node of another account and prefer node identifiers for world masters.
A pre-flight check¶
The world checks its behaviors when it starts and each member checks the code of the world when it joins. You can run the same checks before starting any node, with no network:
import os
import sys
import importlib
from unaiverse.hsm import HybridStateMachine
from unaiverse.utils.misc import analyze_code
WORLD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "src")
sys.path.insert(0, os.path.dirname(WORLD))
roles = sorted(f[:-5] for f in os.listdir(WORLD) if f.endswith(".json"))
for role in roles:
module = importlib.import_module(f"src.{role}")
behav = HybridStateMachine(module.WAgent(proc=None))
behav.load(os.path.join(WORLD, f"{role}.json")) # raises if an action does not exist
print(f"{role}: {len(behav.get_all_states())} states, behavior OK")
shipped = {f: open(os.path.join(WORLD, f), encoding="utf-8").read()
for f in [f"{r}.py" for r in roles] + ["stats.py"] if os.path.exists(os.path.join(WORLD, f))}
print("code check:", "OK" if analyze_code(shipped) else "REFUSED")
Like the world at startup, the script loads each behavior against a dummy agent of its role. It then runs analyze_code on the role files and stats.py in the same way as a member at join time. If you split the code of a role across several files, add the files that your role files import to shipped.
Checklist before publishing¶
- Every role has a JSON behavior and a
WAgentclass. The pre-flight check passes. - Every action returns
TrueorFalseon every branch. - Every request passes
from_stateand the state of the target has the requested action. - Every callback checks
is_completed()and the completion reason. - Recovery from a lost connection exists in every role that depends on another member.
- No action computes for more than a fraction of a second without
stepwise. - The code that the roles import passes
analyze_codeandstats.pyhas no relative imports. - Local resources are read from the environment in
accept_new_role. - People can take part: forms carry a clear
altand every question has a form. - The world masters are declared by node identifier when the world is public.
- Stats and badges record what the community should remember.
- The world node is reachable or offers its relay with TLS for members in the browser.
- The visibility of the world and, if you publish the code,
code_repoandcode_commitare in place.
Where next¶
- Every parameter of every piece used in this path: Worlds, Behaviors, Actions, Interactions.
- A world that people see through a page of its own: A view for your world.
- More worlds to read: Examples.