Skip to content

10 · Stats, badges and going live

A community needs a memory. The teacher knows who attended the last exam, how each student did and whether the class improves over the rounds. This knowledge, however, disappears when its node stops and nobody else can see it. The sixth and last stage of the classroom (tutorial_steps/step6, identical to the final world) gives the world statistics that persist, a page that shows them and a record for every student. The second half of this chapter prepares the world for other people.

A stats class

The world declares what it records in stats.py, with a subclass of Stats named WStats:

src/stats.py (abridged)
from unaiverse.stats import Stats


class WStats(Stats):
    """Per-student quality and exam history of the classroom."""

    MAX_EXAMS_PER_STUDENT = 30

    # Read by the SDK: the stats this world declares, with their type and default
    CUSTOM_OUTER_STATS_DYNAMIC_SCHEMA = {
        "exam_result": (dict, None),
    }

    def _prune_db(self):
        """Called when the stats are saved: keeps the last 30 exams of each student."""
        ...

    def plot(self, since_timestamp: int = 0) -> str | None:
        """Renders the stats page of the world as one HTML document."""
        if not self.is_world:
            return None
        history = self._fetch_exam_history()   # reads the database of the world
        ...
        return "<!DOCTYPE html><html>...</html>"

The class has three parts:

  1. The schema. CUSTOM_OUTER_STATS_DYNAMIC_SCHEMA declares one dynamic stat, a value that changes over time and is stored with a timestamp. Its type is dict so that each record can carry a score, the number of correct answers, the number of questions and the quality index after the exam.
  2. The storage rules. The world keeps its stats in a SQLite database inside the world folder. _prune_db runs every time the stats are saved and deletes the records beyond the last 30 of each student.
  3. The page. plot returns a complete HTML document. The web application shows it as the stats page of the world. The classroom draws one card per student with the quality index as stars and the history of the last exams.

The world creates the stats object and hands it to World:

src/world.py
from .stats import WStats

class WWorld(World):
    def __init__(self, **kwargs):
        world_folder = os.path.dirname(os.path.abspath(__file__))
        stats = WStats(is_world=True, db_path=os.path.join(world_folder, "stats", "world_stats.db"))
        super().__init__(world_folder=world_folder, stats=stats, **kwargs)

Without a stats argument the world creates a plain Stats with its database in stats/world_stats.db.

Recording from the members

Members record stats too. stats.py travels to every member with the grant (chapter 2) and each member creates its own instance of WStats. The teacher stores one record per student at the end of evaluate_results:

timestamp = self.clock.get_time_ms(monotonic=True)
for student, score in student_last_exam_scores.items():
    unaid = build_unaid(self.world_agents[student])
    self.stats.store_stat("exam_result",
                          {"score": score,
                           "correct": details[student].count("✓"),
                           "questions": self.EXAM_SAMPLES,
                           "quality": self.student_quality[student]},
                          group_key=unaid, timestamp=timestamp)

store_stat(stat_name, value, group_key, timestamp) checks the value against the schema and stores it under a group. The classroom groups the records by the identity of the student on the network (build_unaid). This identity stays the same when the student reconnects with a new peer identifier. The member sends its records to the world in batches at regular intervals and the world writes them to its database.

A world can intercept the records as they arrive by overriding _process_custom_stat(stat_name, value, group_key, timestamp) in its World subclass. Returning True tells the world that the method handled the record and the default storage is skipped. The class-incremental learning world of the examples (unaiverse-examples/worlds/class_incremental_learning/src/world.py) uses this hook to track the best accuracy so far.

Querying the stats

A member asks the world for stats with the built-in action ask_world_stats(filters). The world answers in answer_stats_request(filters, asker). The default implementation reads these keys from filters and queries the history of the database:

Key Meaning
stat_names The stats to return (all when empty).
group_keys The groups to return (all when empty).
time_range How far back in time to go.
value_range A numeric filter on the values.
limit The maximum number of records.

The answer arrives later and is merged into the local stats view of the member. A world can override answer_stats_request to apply its own rules, for example to let each student see only its own records. The asker argument identifies who is asking.

Badges from the world

The world can award a badge itself with add_badge. The class-incremental learning world gives one to every new champion:

self.add_badge(peer_id=peer_id, score=value, badge_type="completed",
               badge_description="LOT2.0 champion!",
               agent_token=self.node_conn.get_last_token(peer_id))

score must be in [0, 1] and badge_type one of completed, attended, intermediate and pro. Any other value raises ValueError. agent_token is the last token of the agent and the world reads it from its connection pool. The badges of the world travel with the next update of its profile. get_all_badges() returns the badges added so far and clear_badges() forgets them.

Going live

During development every node of the classroom runs with hidden=True and only your account sees them. Opening the world to other people takes a few decisions.

Visibility

Start the world node with hidden=False or leave hidden=None and choose the visibility in the web application. People of other accounts then find the world by name and by the nickname of your account and join it as "<nickname>/CoLLAsTutorial".

Declaring the source of the world

A world that publishes its code on GitHub can declare where that code lives:

Node(node_name="CoLLAsTutorial", hosted=world, hidden=False,
     code_repo="your-account/collas-world",
     code_commit="<the full 40-character id of a pushed commit>")

code_repo takes "owner/repo" or the full URL of a public repository. code_commit takes the full identifier of a commit that was pushed, never a branch or a tag. The two arguments go together and the node refuses to start when only one of them is given. The root server fetches the repository at that commit and records a digest of the code of the world in the token of the world node. Without the two arguments the world declares nothing and runs unpublished. The SDK fully supports this case. Joins work in the same way in both cases.

Reaching members behind a router

Many members run on machines that do not accept incoming connections. When the world node is publicly reachable, it offers its relay to its members. A member that is not reachable on its own reserves a slot on the relay of the world node when it joins and keeps it alive while it is a member. A browser can use the relay only over TLS. A world node that offers its relay without TLS prints a warning at startup. NODE_USE_TLS=1 turns TLS on and needs DOMAIN, TLS_CERT_PATH and TLS_KEY_PATH as well. Configuration lists these variables.

A page of its own

The web application shows every world as a chat. With the GUI kit you can replace that chat with a page that draws the classroom as a classroom: the current picture, the exam as a grid of buttons, the stars of each student. The page receives every change in the state of the world as it happens and sends messages and actions to the world on behalf of the person who uses it. A view for your world explains what the world must expose and how the page is published.

Restarting after a change

The world packs its code when it starts. After a change to the world folder, restart the world node first and then the members. Each member receives the new code with its next grant.

Run it

Run the final world in the parent folder (or tutorial_steps/step6) with the teacher and two students. After a couple of exams, open the page of the world in the web application. The stats page shows one card per student with its quality stars and its last exams.

Where next

You have seen every part of a world. Chapter 11 starts from an empty folder and builds a smaller world with names of your choice.

11 · Build your first world