Skip to content

clabe.workflow.events

Run events: the append-only, sequenced record of a Run.

Every state change of a run is one of the event models below, appended to the run's EventLog (run.events) and mirrored to events.jsonl when the run keeps records. Event is the discriminated union of all of them (on type); EventLog.read loads a persisted log back.

ActivityEnded

Bases: _Event

Long-running work ended.

ActivityOutput

Bases: _Event

New output lines of a running activity (e.g. a remote job's log), at most about one event per second.

ActivityStarted

Bases: _Event

Long-running work began (e.g. an app is running).

machine class-attribute instance-attribute

machine: str | None = None

The machine it runs on, when not this one (e.g. a job on a leased worker).

ArtifactExported

Bases: _Event

A step saved a file; path is relative to the run's artifacts/ folder.

BranchEnded

Bases: _Event

A branch of a step ended: done, failed (error), cancelled (stopped with the others), or skipped (the user continued without it after it failed).

BranchStarted

Bases: _Event

A branch of a step started (see concurrently); attempt counts its retries.

CommandFinished

Bases: _Event

A command an app ran (Bonsai, Open Ephys, a script) ended: what exactly ran, for provenance.

files maps each existing file the command named (its arguments, its inputs, Bonsai.config next to the program) to its SHA-256 (None when too large to hash). Files of a remote command are hashed here, where the run is (the remote checkout is the same commit when RemoteRepository.verify() passed).

ContextChanged

Bases: _Event

What the run is about changed (or became known): the workflow, the machine, the rig, the subject and the experimenters. Every client shows the latest one prominently; see RunContext.

EventLog

EventLog(run_id: str, path: Path | None = None)

Append-only, sequenced event log, optionally mirrored to a JSON-lines file.

Subscribers are called synchronously, in order, on the appending thread while the log's lock is held, and possibly re-entrantly: an event appended from inside a subscriber reaches the later subscribers before the event being published does. A subscriber must return quickly, must never block on another thread that appends events, and must not call Run methods that take the run's lock (answer, state, abort, go_back, ...): hand such work to a queue or another thread.

Writing the file never fails a run: if a write raises, it is logged once and the file stops being written for the rest of the run, while events are still recorded in memory and published.

Parameters:

Name Type Description Default
run_id str

Stamped on every event.

required
path Path | None

When given, each event is appended to this file as one JSON line.

None
Source code in src/clabe/workflow/_events.py
def __init__(self, run_id: str, path: Path | None = None) -> None:
    self.run_id = run_id
    self.path = path
    self._lock = threading.RLock()
    self._events: list[Event] = []
    self._subscribers: list[Callable[[Event], None]] = []
    self._write_failed = False
    if path is not None:
        path.parent.mkdir(parents=True, exist_ok=True)

last_seq property

last_seq: int

Sequence number of the latest event (0 when empty).

append

append(event: Event) -> Event

Stamps event with the next sequence number and the run id, records and publishes it.

A failure to write the file is logged (once) and stops the mirroring; it is never raised.

Source code in src/clabe/workflow/_events.py
def append(self, event: Event) -> Event:
    """Stamps ``event`` with the next sequence number and the run id, records and publishes it.

    A failure to write the file is logged (once) and stops the mirroring; it is never raised.
    """
    with self._lock:
        event = event.model_copy(update={"seq": len(self._events) + 1, "run_id": self.run_id})
        self._events.append(event)
        if self.path is not None and not self._write_failed:
            try:
                with self.path.open("a", encoding="utf-8") as stream:
                    stream.write(event.model_dump_json() + "\n")
            except Exception:  # a record that cannot be written must not stop the run
                self._write_failed = True
                logger.exception(
                    "Could not write event %s to %s; no longer writing events there", event.seq, self.path
                )
        for subscriber in list(self._subscribers):
            try:
                subscriber(event)
            except Exception:  # one broken client must not break the run
                logger.exception("Event subscriber %r failed", subscriber)
        return event

since

since(seq: int = 0) -> list[Event]

Returns the events after sequence number seq.

Source code in src/clabe/workflow/_events.py
def since(self, seq: int = 0) -> list[Event]:
    """Returns the events after sequence number ``seq``."""
    with self._lock:
        return self._events[seq:]

subscribe

subscribe(
    subscriber: Callable[[Event], None],
) -> Callable[[], None]

Calls subscriber for every future event; returns a function that unsubscribes.

subscriber is called synchronously on the thread that appends the event, with the log's lock held, and possibly re-entrantly (an event appended from inside a subscriber reaches the later subscribers before the event being published does). It must return quickly, must never block on another thread that appends events, and must not call Run methods that take the run's lock (answer, state, abort, go_back, ...): hand such work to a queue or another thread. An exception it raises is logged and otherwise ignored.

Source code in src/clabe/workflow/_events.py
def subscribe(self, subscriber: Callable[[Event], None]) -> Callable[[], None]:
    """Calls ``subscriber`` for every future event; returns a function that unsubscribes.

    ``subscriber`` is called synchronously on the thread that appends the event, with the log's lock held, and
    possibly re-entrantly (an event appended from inside a subscriber reaches the later subscribers before the
    event being published does). It must return quickly, must never block on another thread that appends
    events, and must not call [`Run`][clabe.workflow.Run] methods that take the run's lock (``answer``,
    ``state``, ``abort``, ``go_back``, ...): hand such work to a queue or another thread. An exception it
    raises is logged and otherwise ignored.
    """
    with self._lock:
        self._subscribers.append(subscriber)

    def unsubscribe() -> None:
        with self._lock:
            if subscriber in self._subscribers:
                self._subscribers.remove(subscriber)

    return unsubscribe

read staticmethod

read(path: Path) -> list[Event]

Reads the events persisted at path.

Source code in src/clabe/workflow/_events.py
@staticmethod
def read(path: Path) -> list[Event]:
    """Reads the events persisted at ``path``."""
    lines = path.read_text(encoding="utf-8").splitlines()
    return [_EVENT_ADAPTER.validate_json(line) for line in lines if line]

Header

Bases: _Event

A prominent header for the user.

Notify

Bases: _Event

A message for the user. level is a MessageLevel value.

PromptClosed

Bases: _Event

A prompt was answered (by answered_by) or cancelled.

answer is the JSON form of the accepted answer (secrets stay masked); None when cancelled.

PromptOpened

Bases: _Event

A step is waiting for an answer. answer_schema is the JSON Schema of a valid answer.

When the same prompt was answered before (an earlier attempt of its step asked it; see Run.forward), can_forward is set and previous_answer is that answer, in its JSON form: clients prefill it and offer Forward. Secret answers are never remembered.

RecordResolved

Bases: _Event

A step took a record (a rig, a trainer state, ...) from a store: which one, from where, and its content hash.

The record itself is saved as an artifact of the step (stores/<kind>.json), so the session keeps exactly what it used even if the store changes later.

RunClosed

Bases: _Event

The session was closed: by a client (closed_by), by the deadline ("timeout") or by the launcher.

The last event of a run whose session was kept open (see Run.keep_open).

RunClosing

Bases: _Event

The run has finished and the launcher shows its closing screen, waiting for a client to close the session.

deadline is when it closes on its own (None: it waits for a client). See Run.close.

RunFinished

Bases: _Event

The run ended.

RunStarted

Bases: _Event

The run began executing.

StepFailed

Bases: _Event

A step raised. warn_only steps continue; others pause the run.

StepFinished

Bases: _Event

A step completed.

summary is a truncated rendering of its output, output_sha256 links to its line in outputs.jsonl and inputs gives the attempt of each upstream step whose output it consumed (0: skipped). The attempt of a warn-only failure (whose output is None) has a StepFailed event and no line in outputs.jsonl. output_sha256 is None when the output was omitted or the run keeps no records.

StepsInvalidated

Bases: _Event

Completed steps were reset to pending by going back.

StepSkipped

Bases: _Event

A step was skipped: an optional step declined, or a conditional step whose condition did not hold.

StepStarted

Bases: _Event

A step began running (attempt counts runs of this step, from 1).