This module records the statistics of a world. A world keeps the number of its members, the connectivity graph between them and what each member is doing (its state, its action, its last completed action). Members measure their own values and send them to the world. The world stores them in memory and in a SQLite database and answers the members that ask for them. The same class Stats serves both sides with two modes:
agent mode (is_world=False): the object buffers the values measured by the agent until the node sends them to the world. It also keeps the view of the world statistics received in answer to a request.
world mode (is_world=True): the object keeps a hot cache of the recent values, writes every value to the database and answers queries over the whole history.
The node drives both modes. An agent in a world calls collect_and_store_own_stats() and sends the buffer every Custom.SEND_STATS_EVERY seconds (30 by default). The world merges each batch with World.add_peer_stats() and saves to disk every Custom.SAVE_STATS_EVERY seconds. The module also holds two small builders of Plotly figures (UIPlot and DefaultBaseDash) that Stats.plot() uses to draw the default dashboard.
The current state, the running action and the last completed action of the world behavior of the agent.
A world adds its own statistics with a subclass that fills the CUSTOM_* schemas. The subclass is named WStats and lives in stats.py in the world folder. The world ships this file to every member. It must also use the same class itself because it logs and drops every value whose name is missing from its own schemas.
# stats.py in the world folderfromunaiverse.statsimportStatsclassWStats(Stats):CUSTOM_AGENT_STATS_DYNAMIC_SCHEMA={"accuracy":(float,0.0)}CUSTOM_WORLD_STATS_STATIC_SCHEMA={"leaderboard":(list,[])}
# the worldimportosfromunaiverse.worldimportWorldfrom.statsimportWStatsclassClassroom(World):def__init__(self,**kwargs):folder=os.path.dirname(os.path.abspath(__file__))stats=WStats(is_world=True,db_path=os.path.join(folder,"stats","world_stats.db"))super().__init__(world_folder=folder,stats=stats,**kwargs)
# an action of a member_,own_private_pid=self.get_peer_ids()self.stats.store_stat("accuracy",0.92,group_key=own_private_pid,timestamp=clock.get_time_ms())
The two color palettes of the figures, "dark" and "light". Each palette is a dictionary with the keys bg_paper, bg_plot, text_main, text_light, grid, edge, node_border, main and main_light (CSS colors), table (a dictionary with header_bg, header_txt, cell_bg, cell_txt and line) and peers (a list of ten colors assigned to peers and categories).
The palette THEMES["dark"] used by UIPlot, DefaultBaseDash and Stats.plot(). The builders read the module attribute at each call. Assigning unaiverse.stats.THEME = unaiverse.stats.THEMES["light"] therefore switches the figures built afterwards to the light palette.
def__init__(self,title:str='',height:int=400):"""Initializes a UIPlot with an empty data list and a pre-configured dark-theme layout. Args: title: Title text shown at the top of the plot. height: Height of the plot in pixels. """self._data:list[dict[str,Any]]=[]# Define the standard axis style for a "boxed" lookaxis_style={'gridcolor':THEME['grid'],'gridwidth':1,'griddash':'dot','color':THEME['text_light'],'showline':True,# Draw the axis line'mirror':True,# Mirror it on top/right (creates the box)'linewidth':2,# Width of the box border'linecolor':THEME['grid'],# Color of the box border'zeroline':False,# Prevents double-thick borderlines at 0'layer':'below traces'# Key fix: puts grid BEHIND the box border}self._layout:dict[str,Any]={'title':title,'height':height,'xaxis':{**axis_style,'title':'Time'},'yaxis':{**axis_style,'title':'Value'},'margin':{'l':50,'r':50,'b':50,'t':50},# Default dark theme friendly styling'paper_bgcolor':THEME['bg_paper'],'plot_bgcolor':THEME['bg_plot'],'font':{'color':THEME['text_main']}}
A builder of one Plotly figure (a panel) that collects traces in data and options in layout. The layout starts with transparent backgrounds, dotted grid lines, a box around the plot area and the axis titles Time and Value.
defadd_line(self,x:list[Any],y:list[Any],name:str,color:str|None=None,legend_group:str|None=None,show_legend:bool=True):"""Adds a standard time-series line. Args: x: Sequence of x-axis values (e.g., timestamps). y: Sequence of y-axis values. name: Label shown in the legend. color: CSS color string for the line. Defaults to the primary theme color. legend_group: Plotly legend group name for toggling related traces together. show_legend: Whether to display this trace in the legend. """ifcolorisNone:color=THEME['main']trace={'x':x,'y':y,'name':name,'type':'scatter','mode':'lines+markers','line':{'color':color},"legendgroup":legend_group,"showlegend":show_legend}self._data.append(trace)
Appends a scatter trace drawn with lines and markers from the points x and y. name labels it in the legend and color gives its CSS color (THEME['main'] by default). Traces with the same legend_group are shown and hidden together from the legend. show_legend=False hides the trace from the legend. Returns None.
defadd_area(self,x:list[Any],y:list[Any],name:str,color:str|None=None):"""Adds a filled area chart. Args: x: Sequence of x-axis values. y: Sequence of y-axis values. name: Label shown in the legend. color: CSS color string for the fill/line. Defaults to the primary theme color. """ifcolorisNone:color=THEME['main']trace={'x':x,'y':y,'name':name,'type':'scatter','fill':'tozeroy','line':{'color':color}}self._data.append(trace)
Appends a scatter trace filled down to zero from the points x and y with the legend label name and the CSS color color (THEME['main'] by default). Returns None.
defadd_indicator(self,value:Any,title:str):"""Adds a big number indicator. Args: value: Numeric (or any) value to display prominently. title: Subtitle text rendered below the number. """self._data.append({'type':'indicator','mode':'number','value':value,'title':{'text':title}})self._layout['height']=300# Indicators usually need less height
Appends a big-number indicator that shows value with title below it and lowers the height of the panel to 300 pixels. Returns None.
defadd_table(self,headers:list[str]|None,columns:list[list[Any]]):"""Adds a data table. Args: headers: Column header labels, or ``None`` to hide the header row. columns: Column data as a list of lists, one inner list per column. """num_columns=len(columns)ifcolumnselse0ifheaders:header_cfg={'values':headers,'fill':{'color':THEME['table']['header_bg']},'font':{'color':THEME['table']['header_txt']},'line':{'color':THEME['table']['line']}}else:header_cfg={'values':['']*num_columns,'height':0,# Hide it'fill':{'color':'rgba(0,0,0,0)'},# Transparent just in case'line':{'width':0}# No border}trace={'type':'table','header':header_cfg,'cells':{'values':columns,'fill':{'color':THEME['table']['cell_bg']},'font':{'color':THEME['table']['cell_txt']},'line':{'color':THEME['table']['line']}}}self._data.append(trace)
Appends a table. columns is a list of columns and each column is a list of cells. headers gives the column titles and None (or an empty list) hides the header row. The colors come from THEME['table']. Returns None.
defadd_bar(self,xs:list[Any],ys:list[Any],names:list[str],colors:list[str]|str|None=None):"""Adds a bar chart trace. Args: xs: Category labels for the x-axis. ys: Numeric values for bar heights. names: Text annotations placed on top of each bar. colors: Single CSS color string or a list of per-bar color strings. Defaults to the primary theme color. """ifcolorsisNone:colors=THEME['main']trace={'type':'bar','x':xs,'y':ys,'marker':{'color':colors},'showlegend':False,'text':names,'textposition':'auto'}self._data.append(trace)self._layout['yaxis'].update({'title':'Value'})
Appends a bar chart with the categories xs and the heights ys. names gives the text written on each bar. colors is one CSS color or a list with one color per bar (THEME['main'] by default). The trace is hidden from the legend. Returns None.
defadd_trace(self,trace:dict[str,Any]):"""Generic method to add any raw Plotly trace. Args: trace: A Plotly trace dictionary (e.g., ``{'type': 'scatter', ...}``). """self._data.append(trace)
Appends the Plotly trace trace given as a dictionary. Returns None.
defset_y_range(self,min_val:float,max_val:float):"""Force Y-axis limits. Args: min_val: Lower bound of the Y-axis. max_val: Upper bound of the Y-axis. """self._layout.setdefault('yaxis',{})['range']=[min_val,max_val]
Fixes the range of the y axis to [min_val, max_val]. Returns None.
defset_layout_opt(self,key:str,value:Any):"""Generic setter for advanced layout options. Args: key: Top-level Plotly layout key (e.g., ``'xaxis'``, ``'legend'``). value: Value to assign. If the key already holds a dict and ``value`` is also a dict, the existing dict is updated (merged) rather than replaced. """ifisinstance(value,dict)andkeyinself._layout:self._layout[key].update(value)else:self._layout[key]=value
Writes value under the layout key key. When both the existing value and value are dictionaries, the existing one is updated with the entries of value instead of being replaced. Returns None.
defset_legend(self,orientation:str='v',x:float=1.0,y:float=1.0,xanchor:str='left',yanchor:str='top'):"""Configures the legend position and orientation. Args: orientation: Legend orientation. ``'v'`` for vertical, ``'h'`` for horizontal. x: Horizontal position of the legend anchor in paper coordinates (0–1). y: Vertical position of the legend anchor in paper coordinates (0–1). xanchor: Horizontal alignment of the legend box relative to ``x``. One of ``'left'``, ``'center'``, ``'right'``. yanchor: Vertical alignment of the legend box relative to ``y``. One of ``'top'``, ``'middle'``, ``'bottom'``. """self._layout['showlegend']=Trueself._layout['legend']={'orientation':orientation,'x':x,'y':y,'xanchor':xanchor,'yanchor':yanchor,'bgcolor':THEME['bg_paper'],'bordercolor':THEME['edge'],'borderwidth':1}
Shows the legend and places it. orientation is 'v' or 'h'. x and y are the position of the anchor in paper coordinates between 0 and 1. xanchor ('left', 'center', 'right') and yanchor ('top', 'middle', 'bottom') align the box to the anchor. Returns None.
defto_json(self)->str:"""Serializes the panel to the format the Frontend expects. Returns: JSON string with ``'data'`` and ``'layout'`` keys ready for Plotly. """returnjson.dumps({'data':self._data,'layout':self._layout})
Returns the panel as a JSON string with the keys data and layout, ready for Plotly.newPlot or for render_plotly_html.
def__init__(self,title:str="Network Overview"):"""Initializes the 2x2 grid dashboard with default dark-theme layout. Args: title: Main title displayed at the top of the dashboard. """self.traces=[]self.layout={"title":title,"height":800,"template":"plotly_dark","paper_bgcolor":THEME['bg_paper'],"grid":{"rows":2,"columns":2,"pattern":"independent"},# --- ROW 1 ---# Top Left (Graph)"xaxis1":{"domain":[0,0.48]},"yaxis1":{"domain":[0.56,1]},# "xaxis1": {"domain": [0, 0.48], "visible": False}, # "yaxis1": {"domain": [0.58, 1], "visible": False},# Top Right (Timeseries)"xaxis2":{"domain":[0.52,1]},"yaxis2":{"domain":[0.56,1]},# --- ROW 2 ---# Bot Left (Bar)"xaxis3":{"domain":[0,0.48]},"yaxis3":{"domain":[0,0.44]},# Bot Right (Bar)"xaxis4":{"domain":[0.52,1]},"yaxis4":{"domain":[0,0.44]},"showlegend":True,"legend":{"orientation":"h","y":0.55,"x":0.55,"xanchor":"left","yanchor":"top","bgcolor":"rgba(0,0,0,0)","font":{"color":THEME['text_main']}},"margin":{"l":50,"r":50,"t":80,"b":50}}self._map={"top_left":("xaxis1","yaxis1"),"top_right":("xaxis2","yaxis2"),"bot_left":("xaxis3","yaxis3"),"bot_right":("xaxis4","yaxis4")}
A dashboard of four panels in a 2 by 2 grid with a total height of 800 pixels. The positions are top_left, top_right, bot_left and bot_right. Each position has its own pair of axes and the panels merged into it keep their traces, their axis options and their title.
Argument
Type
Default
Meaning
title
str
"Network Overview"
The title of the dashboard.
Attribute
Type
Meaning
traces
list[dict]
The traces of all panels.
layout
dict
The layout of the grid with one pair of axes per position.
defadd_panel(self,ui_plot:UIPlot,position:str):"""Merges a UIPlot into one of the four fixed grid positions. Args: ui_plot: The UIPlot instance whose traces and layout settings are merged in. position: Grid cell to target. One of ``'top_left'``, ``'top_right'``, ``'bot_left'``, ``'bot_right'``. """ifpositionnotinself._map:returnxa,ya=self._map[position]x_dom=self.layout[xa]["domain"]y_dom=self.layout[ya]["domain"]# Merge Traces# noinspection PyProtectedMemberfortinui_plot._data:nt=t.copy()ifnt.get("type")=="table":nt["domain"]={"x":x_dom,"y":y_dom}else:# Cartesian plots use axis referencesnt["xaxis"]=xa.replace("xaxis","x")nt["yaxis"]=ya.replace("yaxis","y")self.traces.append(nt)# Merge Layoutsrc_l=ui_plot.layoutdest_x=self.layout.setdefault(xa,{})dest_y=self.layout.setdefault(ya,{})if"xaxis"insrc_l:dest_x.update({k:vfork,vinsrc_l["xaxis"].items()ifk!="domain"})if"yaxis"insrc_l:dest_y.update({k:vfork,vinsrc_l["yaxis"].items()ifk!="domain"})# Add Title via Annotationifsrc_l.get("title"):assertisinstance(x_dom,list)assertisinstance(y_dom,list)self.layout:dict[str,list]self.layout.setdefault("annotations",[]).append({"text":f"<b>{src_l['title']}</b>","x":(x_dom[0]+x_dom[1])/2,"y":y_dom[1]+0.02,"xref":"paper","yref":"paper","showarrow":False,"xanchor":"center","yanchor":"bottom","font":{"size":14,"color":THEME['text_main']}})
Merges ui_plot into the cell position. With any other position the method returns without changes and raises no error. Table traces receive the domain of the cell. Every other trace is bound to the axes of the cell. The axis options of the panel are copied to the axes of the cell and the title of the panel becomes a bold annotation above the cell. Returns None.
defto_json(self)->str:"""Serializes the dashboard to the format the Frontend expects. Returns: JSON string with ``'data'`` and ``'layout'`` keys ready for Plotly. """returnjson.dumps({"data":self.traces,"layout":self.layout})
Returns the dashboard as a JSON string with the keys data and layout.
def__init__(self,is_world:bool,db_path:str|None=None,# only needed by the worldcache_window_hours:float=2.0):# only needed by the world"""Initializes the Stats engine in either World or Agent mode. Args: is_world: When ``True``, initializes the full World-side engine including the SQLite database, hot cache, and persistence buffers. When ``False``, initializes a lightweight Agent-side buffer. db_path: Filesystem path for the SQLite database file. Required when ``is_world`` is ``True``; ignored otherwise. cache_window_hours: Duration (in hours) of the in-memory rolling window kept by the World hot cache. Older dynamic data is evicted from RAM while remaining on disk. """self.is_world:bool=is_worldself.max_seen_timestamp:int=0# --- Integrate custom statistics ---self.WORLD_STATS_STATIC_SCHEMA=self.CORE_WORLD_STATS_STATIC_SCHEMA|self.CUSTOM_WORLD_STATS_STATIC_SCHEMAself.WORLD_STATS_DYNAMIC_SCHEMA=self.CORE_WORLD_STATS_DYNAMIC_SCHEMA|self.CUSTOM_WORLD_STATS_DYNAMIC_SCHEMAself.AGENT_STATS_STATIC_SCHEMA=self.CORE_AGENT_STATS_STATIC_SCHEMA|self.CUSTOM_AGENT_STATS_STATIC_SCHEMAself.AGENT_STATS_DYNAMIC_SCHEMA=self.CORE_AGENT_STATS_DYNAMIC_SCHEMA|self.CUSTOM_AGENT_STATS_DYNAMIC_SCHEMAself.OUTER_STATS_STATIC_SCHEMA=self.CORE_OUTER_STATS_STATIC_SCHEMA|self.CUSTOM_OUTER_STATS_STATIC_SCHEMAself.OUTER_STATS_DYNAMIC_SCHEMA=self.CORE_OUTER_STATS_DYNAMIC_SCHEMA|self.CUSTOM_OUTER_STATS_DYNAMIC_SCHEMA# --- Master key sets for easier lookup ---self.all_static_keys:set[str]=set()self.all_dynamic_keys:set[str]=set()self.all_keys:set[str]=set()self.world_grouped_keys:set[str]=set()self.world_ungrouped_keys:set[str]=set()self.agent_grouped_keys:set[str]=set()self.agent_ungrouped_keys:set[str]=set()self.stat_types:dict[str,type]={}self._stat_defaults:dict[str,Any]={}self._initialize_key_sets()ifself.is_world:# --- World Configuration ---self._stats:dict[str,Any]={self.GROUP_KEY:{}}self.min_window_duration=timedelta(hours=cache_window_hours)self.db_path=db_pathself._db_conn:sqlite3.Connection|None=Noneself._static_db_buffer=[]self._dynamic_db_buffer=[]# --- World Initialization ---self._init_db()# Connect and create tablesself._initialize_cache_structure()# Ensures all keys existself._load_existing_stats()# Hydrates _stats from diskelse:# --- Agent Initialization (Simple Buffer) ---self._world_view:dict[str,Any]={}self._update_batch:list[dict[str,Any]]=[]
The statistics of a world or of an agent. The world creates one in world mode (see World) and every Agent creates one in agent mode. When the bundle received from the world contains stats.py, a member replaces its Stats object with an instance of WStats.
Argument
Type
Default
Meaning
is_world
bool
required
True for world mode and False for agent mode.
db_path
str \| None
None
World mode only. The path of the SQLite file. The parent folder is created when missing.
cache_window_hours
float
2.0
World mode only. The span of the hot cache in hours. Older time-series values leave memory and stay in the database.
In world mode the constructor opens the database in WAL mode, creates the tables dynamic_stats and static_stats when missing and reloads the time-series values of the last cache_window_hours into the cache. Static values are not reloaded. A failure to open the database is printed to standard output and leaves the object without persistence.
The schemas that a subclass fills. Each maps a name to (type, default) and is merged with the matching core schema at construction.
STORE_DYNAMIC_IF_CHANGED
False
With True a dynamic value equal to the last one is not stored. Because the comparison reads the ungrouped value of the name, the option affects only the statistics of the world.
GROUP_KEY
'peer_stats'
The key of the cache that holds the grouped statistics.
DEBUG
False
Deprecated and not read.
Attribute
Type
Meaning
is_world
bool
The mode.
max_seen_timestamp
int
The largest timestamp in milliseconds stored or received.
defstore_stat(self,stat_name:str,value:Any,group_key:str,timestamp:int):"""Unified API to store a stat. Dispatches to static or dynamic storage. Args: stat_name: Name of the statistic as defined in one of the schema dicts. value: Value to store. Type-validated and cast according to the schema. group_key: Grouping key for this stat (e.g. the sender's peer id, or any arbitrary identifier used to bucket related records together). timestamp: Millisecond Unix timestamp associated with the measurement. """ifstat_namenotinself.all_keys:log.error(f'Stat "{stat_name}" is not defined')return# disambiguate between static and dynamic statsifstat_nameinself.all_static_keys:self._store_static(stat_name,value,group_key,timestamp)else:self._store_dynamic(stat_name,value,group_key,timestamp)
Stores one value and returns None. An unknown stat_name is logged as an error and ignored. The value is first converted to the type of the schema. A value of another type goes through the type constructor (float("0.5") gives 0.5) and a value rejected by the constructor is logged and stored as str(value). group_key is the peer the value refers to and timestamp is the time of the measurement in milliseconds (clock.get_time_ms()).
In agent mode the value goes to the buffer that the node sends to the world. A static value replaces the buffered value with the same name and group key and a dynamic value is appended. In world mode a static value replaces the cached one and a dynamic value enters the time series of its name (ungrouped) or of its group key (grouped). Values more than cache_window_hours older than the new one are removed from the series. An ungrouped series keeps one value at the edge of the window so that the line stays continuous. Every value is also queued for the next save_to_disk().
defget_last_value(self,stat_name:str,group_key:str|None=None)->Any|None:"""Returns the most recent value of any stat, whether static or dynamic. Args: stat_name: Name of the statistic to retrieve. group_key: When ``None``, looks up an ungrouped (world-level) stat. When provided, looks up the grouped stat under that key. Returns: The most recent value, or ``None`` if the stat is unknown or has no data. """ifstat_nameinself.all_static_keys:returnself._get_last_static_value(stat_name,group_key)elifstat_nameinself.all_dynamic_keys:returnself._get_last_dynamic_value(stat_name,group_key)else:log.error(f'get_last_value: Unknown stat_name "{stat_name}"')returnNone
Returns the last value of stat_name for group_key (None for an ungrouped statistic) and None when there is none. In world mode the value comes from the cache. In agent mode the method reads a dynamic value from the buffer not yet sent and always returns None for a static statistic. An unknown name is logged as an error.
defget_stats(self)->dict[str,Any]:"""Returns the raw internal stats dictionary (World-only). Returns: The ``_stats`` hot-cache dictionary containing ungrouped world stats and the peer-grouped stats keyed by ``GROUP_KEY``. """returnself._stats
World mode only. Returns the cache itself (not a copy). The cache maps the name of each ungrouped statistic to its value and holds under the key GROUP_KEY a dictionary from group key to the grouped statistics. Time series are sortedcontainers.SortedDict objects keyed by timestamp. In agent mode the call raises AttributeError.
defget_payload_for_world(self,clear_buffer:bool=True)->list[dict[str,Any]]:"""(Agent-only) Gathers, returns, and clears all pending stats to be sent to the world. Args: clear_buffer: Whether to clear the stats buffer after the get operation (default True). Returns: List of stat update dicts, each with ``'peer_id'``, ``'stat_name'``, ``'timestamp'``, and ``'value'`` keys. Returns an empty list on the World side. """ifself.is_world:return[]# self._update_agent_static() # Ensure static stats are fresh in the batchpayload=self._update_batchifclear_buffer:self._update_batch=[]# Clear after gettingreturnpayload
Agent mode. Returns the buffer of values to send to the world as a list of dictionaries with the keys group_key, stat_name, timestamp and value. The default clear_buffer=True empties the buffer. In world mode the result is []. The agent calls it in send_stats_to_world().
defupdate_view(self,view_data:dict[str,Any]|None=None,overwrite:bool=False):"""(Agent-side) Merges a snapshot received from the World into the local view. This is 'dumb' storage: the data is kept as-is for later plotting without further parsing. Dynamic stats are extended (appended) rather than replaced unless ``overwrite`` is set. Expected ``view_data`` structure:: { "world": { "stat_name": value_or_timeseries }, "peers": { "peer_id": { "stat_name": value_or_timeseries } } } For dynamic stats, each ``value_or_timeseries`` is a list of ``[timestamp, value]`` pairs for efficient JSON/Plotly usage. Args: view_data: The snapshot received from the world. overwrite: If ``True``, discards the current view before merging the new data. """ifself.is_world:return# Initialize empty structure if neededifnotself._world_vieworoverwrite:self._world_view={'world':{},'peers':{}}def_update_max_ts(ts):"""Helper to update the max seen timestamp from a time-series."""# Dynamic stats come as [[ts, val], [ts, val]...]ifisinstance(ts,list)andlen(ts)>0andisinstance(ts[0],list):# The last item is usually the newest in sorted time-serieslast_ts=ts[-1][0]iflast_ts>self.max_seen_timestamp:self.max_seen_timestamp=int(last_ts)def_merge_dict(target:dict,source:dict):""" Helper to merge source into target with special handling for dynamic stats. Copies a source dict { "stat_name": value_or_timeseries } into target. """forstat_name,val_or_tsinsource.items():ifstat_nameinself.all_dynamic_keys:_update_max_ts(val_or_ts)ifstat_namenotintarget:target[stat_name]=[]target[stat_name].extend(val_or_ts)else:target[stat_name]=val_or_ts# 1. Merge World (Ungrouped) Statsassertview_dataisnotNoneif'world'inview_data:_merge_dict(self._world_view.setdefault('world',{}),view_data['world'])# 2. Merge Peer (Grouped) Statsif'peers'inview_data:target_peers=self._world_view.setdefault('peers',{})forpeer_id,peer_datainview_data['peers'].items():target_peer=target_peers.setdefault(peer_id,{})_merge_dict(target_peer,peer_data)
Agent mode. Merges into the local view the dictionary view_data that the world sent in the view format. The pairs of a dynamic statistic are appended to the pairs already present and any other value replaces the previous one. overwrite=True discards the local view first. In world mode the call does nothing. The agent calls it when an answer to ask_world_stats arrives. Returns None.
defget_view(self,since_timestamp:int=0)->dict[str,Any]:"""(World-side) Returns a JSON-serializable snapshot of the current in-memory cache. Used for initial handshakes or lightweight polling. Dynamic stats are filtered to only include entries newer than ``since_timestamp``. Args: since_timestamp: Millisecond Unix timestamp. Only dynamic data points with a timestamp strictly greater than this value are included. Pass ``0`` to include all cached data. Returns: Dictionary with the structure:: { "world": { "stat_name": value_or_timeseries }, "peers": { "peer_id": { "stat_name": value_or_timeseries } } } For dynamic stats, ``value_or_timeseries`` is a list of ``[timestamp, value]`` pairs. Returns an empty dict when called on the Agent side. """ifnotself.is_world:return{}snapshot={'world':{},'peers':{}}# 1. Process World (Ungrouped) Statsforstat_nameinself.world_ungrouped_keys:val=self._stats.get(stat_name)ifvalisnotNone:snapshot['world'][stat_name]=self._serialize_value(val,since_timestamp)# 2. Process Peer (Grouped) Statspeer_groups=self._stats.get(self.GROUP_KEY,{})forpidinpeer_groups.keys():peer_data={}forstat_name,valinpeer_groups[pid].items():serialized=self._serialize_value(val,since_timestamp)# Optimize: Don't send empty lists if pollingifisinstance(serialized,list)andlen(serialized)==0:continuepeer_data[stat_name]=serializedifpeer_data:snapshot['peers'][pid]=peer_datareturnsnapshot
World mode. Returns the content of the cache in the view format. Only the time-series values with a timestamp greater than or equal to since_timestamp are included (all of them with the default 0) and a peer whose series are all empty after this filter is omitted. In agent mode the result is {}.
defquery_history(self,stat_names:list[str]|None=None,group_keys:list[str]|None=None,time_range:tuple[int,int]|int|None=None,value_range:tuple[float,float]|None=None,limit:int|None=None)->dict[str,Any]:"""(World-only) Queries the SQLite DB for historical stats with optional filters. Automatically flushes the current memory buffers to the DB before querying to ensure "read-your-writes" consistency. Returns the same structure as ``get_view()``, so the Agent can ingest it seamlessly. Args: stat_names: Restrict results to these stat names. Pass ``None`` or ``[]`` to include all stats. group_keys: Restrict results to these group keys. Pass ``None`` or ``[]`` to include all groups. time_range: Time filter for dynamic stats. An ``int`` is treated as a "since X" lower bound; a ``(start, end)`` tuple filters to the closed interval ``[start, end]``. Pass ``None`` for no time filter. value_range: ``(min, max)`` numeric range filter applied to ``val_num``. Rows without a numeric value are excluded when this filter is active. limit: Maximum number of dynamic-stat rows to return. Defaults to 5000. Returns: Dictionary with the same structure as ``get_view()``. Returns an empty dict when called on the Agent side or when the DB connection is unavailable. """ifnotself.is_worldornotself._db_conn:return{}def_as_str_list(v):"""Filters arrive from the network: accept only lists of non-empty strings."""return[sforsinvifisinstance(s,str)andlen(s)>0] \
ifisinstance(v,(list,tuple))else[]stat_names=_as_str_list(stat_names)group_keys=_as_str_list(group_keys)ifnot(isinstance(time_range,int)andnotisinstance(time_range,bool))and \
not(isinstance(time_range,(tuple,list))andlen(time_range)==2andall(isinstance(t,(int,float))andnotisinstance(t,bool)fortintime_range)):time_range=Noneifnot(isinstance(value_range,(tuple,list))andlen(value_range)==2andall(isinstance(x,(int,float))andnotisinstance(x,bool)forxinvalue_range)):value_range=None# Flush the cached updates to db before queryingself._save_static_to_db()self._save_dynamic_to_db()self._db_conn.commit()snapshot={'world':{},'peers':{}}# A. Query the static statsquery_static=['SELECT peer_id, stat_name, val_json FROM static_stats']params_static=[]where_added=Falseifstat_names:query_static.append("WHERE")where_added=Truequery_static.append(f"stat_name IN ({','.join(['?']*len(stat_names))})")params_static.extend(stat_names)ifgroup_keys:ifnotwhere_added:query_static.append("WHERE")else:query_static.append(f"AND")query_static.append(f"peer_id IN ({','.join(['?']*len(group_keys))})")params_static.extend(group_keys)try:rows=self._db_conn.execute(' '.join(query_static),params_static).fetchall()exceptExceptionase:log.error(f'Query history (static) failed: {e}')rows=[]forpid,sname,vjsoninrows:try:val=self._validate_type(sname,json.loads(vjson))# Handle special Graph reconstruction if needed (legacy format support)ifsname=='graph':# Handle both legacy format (just edges) and new format (nodes+edges) safelyifisinstance(val,dict)and'edges'inval:# Convert the edge lists back to setsval['edges']={k:set(v)fork,vinval['edges'].items()}# Ensure nodes dict existsif'nodes'notinval:val['nodes']={}else:val:dict# Convert entire dict to sets (as it was before)edges_set={k:set(v)fork,vinval.items()}# Migrate to new structure on the flyval={'nodes':{},'edges':edges_set}# Static stats format: value (direct)ifpidin(None,'None',''):snapshot['world'][sname]=valelse:snapshot['peers'].setdefault(pid,{})[sname]=valexceptExceptionase:log.error(f'Query history: skipping static row ({sname}, {pid}): {e}')# B. Query the dynamic statsconditions,params_dyn=[],[]ifstat_names:conditions.append(f"stat_name IN ({','.join(['?']*len(stat_names))})")params_dyn.extend(stat_names)ifgroup_keys:conditions.append(f"peer_id IN ({','.join(['?']*len(group_keys))})")params_dyn.extend(group_keys)iftime_rangeisnotNone:ifisinstance(time_range,int):conditions.append("timestamp >= ?")params_dyn.append(time_range)elifisinstance(time_range,(tuple,list))andlen(time_range)==2:conditions.append("timestamp >= ? AND timestamp <= ?")params_dyn.extend([time_range[0],time_range[1]])ifvalue_range:conditions.append("val_num IS NOT NULL AND val_num >= ? AND val_num <= ?")params_dyn.extend([value_range[0],value_range[1]])query_dyn=['SELECT timestamp, peer_id, stat_name, val_num, val_str, val_json FROM dynamic_stats']ifconditions:query_dyn.append("WHERE "+" AND ".join(conditions))query_dyn.append("ORDER BY timestamp ASC")try:limit=max(1,min(int(limit),5000))iflimitisnotNoneelse5000except(ValueError,TypeError):limit=5000query_dyn.append(f"LIMIT {limit}")try:rows=self._db_conn.execute(' '.join(query_dyn),params_dyn).fetchall()exceptExceptionase:log.error(f'Query history (dynamic) failed: {e}')rows=[]forts,pid,sname,vnum,vstr,vjsoninrows:try:val=vnumifvnumisnotNoneelse \
(vstrifvstrisnotNoneelse(json.loads(vjson)ifvjsonisnotNoneelseNone))ifvalisNone:continue# Row with no value in any of the three columns: nothing to reportval=self._validate_type(sname,val)ifpidin(None,'None',''):target_ts=snapshot['world'].setdefault(sname,[])else:target_ts=snapshot['peers'].setdefault(pid,{}).setdefault(sname,[])target_ts.append([int(ts),val])exceptExceptionase:log.error(f'Query history: skipping dynamic row ({sname}, {pid}, {ts}): {e}')returnsnapshot
World mode. Queries the database and returns a dictionary in the view format. The method first writes the pending values to the database. Because the filters arrive from the network, the method validates them and drops every filter of the wrong type.
Argument
Type
Default
Meaning
stat_names
list[str] \| None
None
The names to return. None or an empty list means all. Elements that are not non-empty strings are dropped.
group_keys
list[str] \| None
None
The group keys to return. The rules of stat_names apply.
time_range
int \| tuple[int, int] \| None
None
Keeps the time-series rows from an instant on (int) or within a closed interval (pair). Both forms are in milliseconds.
value_range
tuple[float, float] \| None
None
Keeps the time-series rows with a numeric value in the closed interval and drops the others.
limit
int \| None
None
The maximum number of time-series rows, between 1 and 5000. None and invalid values mean 5000. Because the rows are sorted by increasing time, the limit keeps the oldest ones.
Static rows are filtered by name and group key alone. A row whose group key is empty or None goes under world and any other row goes under peers. The counters of the world are stored with the private peer id of the world as group key and therefore come back under peers. On the other hand get_view() puts them under world. The edges of graph come back as sets. In agent mode or without database the result is {}.
defsave_to_disk(self):"""(World-only) Saves the static snapshot and dynamic buffer to SQLite."""ifnotself.is_worldornotself._db_conn:returnlog.debug('Saving world stats to DB...')try:self._save_static_to_db()self._save_dynamic_to_db()self._prune_cache()self._prune_db()self._db_conn.commit()log.debug('Save complete.')exceptExceptionase:log.error(f'CRITICAL: Save_to_disk failed: {e}')ifself._db_conn:self._db_conn.rollback()
World mode. Writes the pending values to the database and commits the transaction. Static values are upserted by group key and name. Time-series values are inserted and a value with the same group key, name and timestamp as a stored one is ignored. The method then prunes the cache in two steps: (1) the time series lose the values older than the window ending at max_seen_timestamp and (2) every peer whose time series are all empty leaves memory. A peer with static statistics alone (the default case for members) leaves memory too. Its state and actions return to the cache only when it sends its next batch. An error rolls the transaction back and is logged. The node calls it every Custom.SAVE_STATS_EVERY seconds. Returns None.
defshutdown(self)->None:"""Flushes pending stats and closes the SQLite connection. Call this explicitly when the application is shutting down to ensure all buffered data is persisted. On the Agent side this is a no-op. """ifself.is_worldandself._db_conn:log.debug('Shutdown: Saving final stats...')try:self.save_to_disk()exceptExceptionase:log.error(f'Shutdown save failed: {e}')self._db_conn.close()self._db_conn=Nonelog.debug('SQLite connection closed.')
World mode. Calls save_to_disk() and closes the database. The node calls it when it stops. In agent mode the call does nothing. Returns None. When the database is still open, the destructor of the object also saves the pending values and closes it.
defplot(self,since_timestamp:int=0)->str|None:"""Builds and returns the default 2x2 dashboard as a self-contained HTML document. Visualizes core stats: network topology, agent-count history, state distribution, and last-action distribution. Plotly.js is loaded from CDN; Python never imports the plotly package. Args: since_timestamp: Millisecond Unix timestamp. Only dynamic data points newer than this value are included in the time-series panels. Pass ``0`` to include all cached data. Returns: HTML string (``<!DOCTYPE html>`` document), or ``None`` if no view data is available. """from.stats_html_rendererimportrender_plotly_html# 1. Get Data viewview=self.get_view(since_timestamp)ifself.is_worldelseself._world_viewifnotview:returnNonedash=DefaultBaseDash("World Overview")# --- Panel 1: Network Topology (Top Left) ---p1=UIPlot(title="World Topology")self._populate_graph(p1,view,"graph")clean_axis={'showgrid':False,'showticklabels':False,'zeroline':False}p1.set_layout_opt('xaxis',clean_axis)p1.set_layout_opt('yaxis',clean_axis)dash.add_panel(p1,"top_left")# --- Panel 2: System Counters (Table) ---p2=UIPlot(title="World Agents History")metrics=[("world_masters","World Masters",THEME['peers'][0]),("world_agents","World Agents",THEME['peers'][1]),("human_agents","Human Agents",THEME['peers'][2]),("artificial_agents","Artificial Agents",THEME['peers'][3]),]forstat_key,label,colorinmetrics:self._populate_time_series(panel=p2,view=view,stat_name=stat_key,color_override=color,title_override=label)p2.set_layout_opt('xaxis',{'title':None,'showticklabels':False})p2.set_layout_opt('yaxis',{'title':None})dash.add_panel(p2,"top_right")# --- Panel 3: State Distribution (Bar) ---p3=UIPlot(title="State Distribution")self._populate_graph(p3,view,"graph")clean_axis={'showgrid':False,'showticklabels':False,'zeroline':False}p3.set_layout_opt('xaxis',clean_axis)p3.set_layout_opt('yaxis',clean_axis)p3.set_layout_opt("xaxis",{"title":None})dash.add_panel(p3,"bot_left")# --- Panel 4: Action Distribution (Bar) ---p4=UIPlot(title="Last Action Distribution")self._populate_distribution(p4,view,"last_action")p4.set_layout_opt("xaxis",{"title":None})dash.add_panel(p4,"bot_right")returnrender_plotly_html(dash.to_json())
Builds the default dashboard and returns it as a complete HTML document (see render_plotly_html). In world mode the data come from get_view(since_timestamp). In agent mode they come from the local view and since_timestamp is ignored. The result is None when the local view of an agent is empty.
Position
Title
Content
top left
World Topology
The connectivity graph with the peers on a circle. Hovering a node shows its name, owner, role, type, number of badges, current action and current state.
top right
World Agents History
The time series of world_masters, world_agents, human_agents and artificial_agents.
bottom left
State Distribution
The connectivity graph again. In the current version this content does not match the title because it shows no distribution of states.
bottom right
Last Action Distribution
A bar chart with the number of peers whose last_action has each value.
The node of a world sends this HTML in answer to a statistics request without stat_names and to a person who joins the world. A WStats subclass may override the method to draw its own dashboard with UIPlot and DefaultBaseDash.