Skip to content

clabe.workflow

Declared workflows and the run runtime that executes them.

BranchesStopped

BranchesStopped(branch: str, error: BaseException)

Bases: Exception

Every branch was stopped because branch failed and the user chose to stop them all.

Source code in src/clabe/workflow/_branches.py
def __init__(self, branch: str, error: BaseException) -> None:
    super().__init__(f"Stopped all branches after {branch!r} failed: {error}")
    self.branch = branch
    self.error = error

Issue dataclass

Issue(
    severity: Severity,
    message: str,
    workflow: str | None = None,
    step: str | None = None,
    source: str | None = None,
)

A problem found by a static check.

Attributes:

Name Type Description
severity Severity

"error" always fails a check; "warning" fails only in strict mode.

message str

What is wrong and how to fix it.

workflow str | None

The workflow concerned, if any.

step str | None

The step concerned, if any.

source str | None

The file checked, when the issue comes from check_path.

RunContext

Bases: BaseModel

What a run is about, as far as known so far: every client shows it prominently (the TUI's header, the web UI's summary strip).

The subject and experimenters are known once the session is (launcher.register_session, or a step returning a session). The rig is the aibs_comp_id environment variable of the machine running the run, and only that: a workflow cannot set it.

Abort

Abort(reason: str = 'Aborted.')

Bases: Exception

Raised by a step to end the run as aborted (not failed).

Source code in src/clabe/workflow/_control.py
def __init__(self, reason: str = "Aborted.") -> None:
    super().__init__(reason)
    self.reason = reason

GoBack

GoBack(to: str | Callable[..., Any] | None = None)

Bases: Exception

Raised by a step to go back to an earlier step.

Raising GoBack with the step's own name runs the step again; a step that does so without asking anything first will loop.

Parameters:

Name Type Description Default
to str | Callable[..., Any] | None

The step to go back to: its name, or its function (GoBack(subject); found by identity, so it works for a step declared with name=). None goes back to the nearest earlier step that has run and is not locked by a completed barrier.

None
Source code in src/clabe/workflow/_control.py
def __init__(self, to: str | Callable[..., Any] | None = None) -> None:
    super().__init__(to)
    self.to = to

ExperimentInfo

Bases: BaseModel

A workflow offered by an experiment file, as listed by list_experiments.

ExperimentListing

Bases: BaseModel

What an experiment file or directory offers (see clabe list).

LocalClient

LocalClient(
    run: Run, client: Client, *, name: str = "local"
)

Answers a run's prompts with a local Client and renders its messages.

The client only collects raw answers: the run validates them, and a rejected answer is shown to the user (with the reason) and asked again. A prompt answered before is shown prefilled with that answer (see prefill), and a client may raise NavigationRequested to go back (Run.back) or forward (Run.forward).

A client with a set_context hook (the terminal UI) is given what the run is about (RunContext) whenever it changes, to show it prominently.

A client with a set_reporter hook (the terminal UI) is given one for the run, so its user can report an issue (see report_run); it stays set after the run, for the closing prompt.

drive must run on the main thread (it is where Ctrl+C lands). The first Ctrl+C aborts the run; a second one propagates as KeyboardInterrupt.

Parameters:

Name Type Description Default
run Run

The run to drive (not yet started).

required
client Client

The console/TUI client used to ask and render.

required
name str

Client name recorded on answers.

'local'
Source code in src/clabe/workflow/_local.py
def __init__(self, run: Run, client: Client, *, name: str = "local") -> None:
    self._run = run
    self._client = client
    self._name = name
    self._prompts: queue.Queue[PromptOpened | None] = queue.Queue()
    self._lock = threading.Lock()
    self._asking: str | None = None
    self._answered_elsewhere: str | None = None  # the prompt we are asking, once another client answered it

drive

drive() -> None

Starts the run and serves it until it finishes.

Raises:

Type Description
KeyboardInterrupt

Ctrl+C was pressed a second time (the run is aborted, not awaited).

Exception

Whatever the client raised; the run is aborted first so it never waits on this client.

Source code in src/clabe/workflow/_local.py
def drive(self) -> None:
    """Starts the run and serves it until it finishes.

    Raises:
        KeyboardInterrupt: Ctrl+C was pressed a second time (the run is aborted, not awaited).
        Exception: Whatever the client raised; the run is aborted first so it never waits on this client.
    """
    set_reporter = getattr(self._client, "set_reporter", None)
    if callable(set_reporter):
        set_reporter(self.report)
    unsubscribe = self._run.events.subscribe(self._on_event)
    interrupted = False
    started = False  # a run this client did not start is someone else's: never abort it
    try:
        self._run.start()
        started = True
        while True:
            try:
                try:
                    item = self._prompts.get(timeout=0.1)
                except queue.Empty:
                    if self._run.wait(0):  # finished, but its RunFinished never reached us
                        break
                    continue
                if item is None:
                    break
                self._answer(item)
            except KeyboardInterrupt:
                if interrupted:
                    raise
                interrupted = True
                self._run.abort("Interrupted by user.")
                self._client.notify("Aborting… press Ctrl+C again to force quit.", MessageLevel.WARNING)
    except KeyboardInterrupt:
        if started:
            self._run.abort("Interrupted by user.")  # no-op if already aborting or finished
        raise
    except BaseException:
        if started and not self._run.wait(0):
            self._run.abort("The local client failed.")
            self._run.wait(5)  # let it record its end; never block on a step that ignores the abort
        raise
    finally:
        unsubscribe()
        with self._lock:  # an interrupt inside _answer's cleanup must not leave a cancel thread spinning
            self._asking = None
    self._run.wait()

report

report(comment: str) -> str

Files an issue report about the run with comment (from this client); returns the report's id.

Source code in src/clabe/workflow/_local.py
def report(self, comment: str) -> str:
    """Files an issue report about the run with ``comment`` (from this client); returns the report's id."""
    from ..reports import report_run  # lazily: clabe.reports is only needed when someone reports

    return report_run(self._run, comment, reported_from=self._name).report_id

ReplayClient

ReplayClient(events: Iterable[Event] | str | Path)

Answers each prompt with the next answer of a recorded session, checking it is the same question.

Prompts are matched in order: the n-th prompt the run asks gets the n-th recorded answer, provided its kind and label are the recorded ones. Answers are validated by the run as any client's are. Commands given outside prompts (clicking a step to go back, aborting) are not replayed; answers given through prompts (a review's "Go back", a failed step's "Retry") are. Secret answers are recorded masked and cannot be replayed.

Use it to reproduce a session's decisions, or as a test of a workflow: record a session once, then replay it after changing the workflow (clabe replay events.jsonl experiment.py).

Parameters:

Name Type Description Default
events Iterable[Event] | str | Path

The recorded session's events, or the path of its events.jsonl.

required
Source code in src/clabe/workflow/_replay.py
def __init__(self, events: Iterable[Event] | str | Path) -> None:
    if isinstance(events, str | Path):
        events = EventLog.read(Path(events))
    opened: dict[str, PromptOpened] = {}
    self._answers: deque[tuple[PromptOpened, Any]] = deque()
    for event in events:
        if isinstance(event, PromptOpened):
            opened[event.prompt_id] = event
        elif isinstance(event, PromptClosed) and event.outcome == "answered" and event.prompt_id in opened:
            self._answers.append((opened[event.prompt_id], event.answer))
    self.replayed = 0

remaining property

remaining: int

Recorded answers not used yet.

ask

ask(request: Request) -> Any

The next recorded answer, after checking it answered the same question.

Source code in src/clabe/workflow/_replay.py
def ask(self, request: Request) -> Any:
    """The next recorded answer, after checking it answered the same question."""
    asked = _describe(request.prompt_kind, request.spec())
    if not self._answers:
        raise ReplayMismatch(f"The recorded session has no answer left for {asked}: the run asks more than it did.")
    recorded, answer = self._answers.popleft()
    expected = _describe(recorded.kind, recorded.spec)
    if expected != asked:
        raise ReplayMismatch(f"The run asks {asked}, but the recorded session answered {expected} at this point.")
    if answer == _MASK:
        raise ReplayMismatch(
            f"The recorded answer to {asked} is a secret, which is not recorded: it cannot be replayed."
        )
    self.replayed += 1
    logger.info("Replaying %s: %r", asked, answer)
    return answer

cancel

cancel() -> None

Nothing to cancel: answers are immediate.

Source code in src/clabe/workflow/_replay.py
def cancel(self) -> None:
    """Nothing to cancel: answers are immediate."""

notify

notify(message: str, level: MessageLevel = INFO) -> None

Logs the message.

Source code in src/clabe/workflow/_replay.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Logs the message."""
    logger.log(MessageLevel(level).logging_level, "%s", message)

header

header(text: str) -> None

Logs the header.

Source code in src/clabe/workflow/_replay.py
def header(self, text: str) -> None:
    """Logs the header."""
    logger.info("%s", text)

close

close() -> None

Nothing to tear down.

Source code in src/clabe/workflow/_replay.py
def close(self) -> None:
    """Nothing to tear down."""

ReplayMismatch

Bases: RuntimeError

The run asked something the recorded session did not answer at that point.

Ack dataclass

Ack()

A command or answer was accepted.

ClosingState

Bases: BaseModel

The closing screen of a finished run (see Run.begin_closing).

Rejected dataclass

Rejected(reason: str)

A command or answer was refused; reason is shown to the client.

Run

Run(
    workflow: Workflow,
    *,
    launcher: Launcher | None = None,
    record_dir: Path | None = None,
    run_id: str | None = None,
)

One execution of a workflow.

Steps run on a dedicated run thread, which has no running event loop: a sync step may run its own (e.g. asyncio.run). Async steps run on one event loop per run, on a thread of its own, so tasks they create (e.g. an app's background task) and loop-bound objects carry across steps; tasks still running when the run ends are cancelled. Every state change is recorded in events. Commands (answers, go back, abort) are thread-safe and may come from any client.

While it executes, the run is the process' Session: ui.ask, the typed helpers (e.g. ui.confirm), ui.notify and ui.header called from steps, from library code and from any thread reach it. One run per process is supported.

Parameters:

Name Type Description Default
workflow Workflow

The workflow to execute. The run keeps a copy (workflow) of its steps as they are when the run is created; later changes to workflow do not affect the run.

required
launcher Launcher | None

Passed to steps that take a launcher parameter.

None
record_dir Path | None

When given, the run's records are written there: events.jsonl, outputs.jsonl (one line per completed step attempt) and artifacts/ (see export_artifact).

None
run_id str | None

Identifier of the run; generated when omitted.

None
Source code in src/clabe/workflow/_run.py
def __init__(
    self,
    workflow: Workflow,
    *,
    launcher: "Launcher | None" = None,
    record_dir: Path | None = None,
    run_id: str | None = None,
) -> None:
    self.id = run_id or uuid.uuid4().hex[:12]
    # A copy: steps added to or replaced in ``workflow`` after the run is created do not change what it runs.
    self.workflow = workflow.variant(workflow.name)
    self.launcher = launcher
    self.record_dir = record_dir
    self.events = EventLog(self.id, record_dir / "events.jsonl" if record_dir is not None else None)
    self.status = RunStatus.CREATED
    self.reason: str | None = None
    self.error: BaseException | None = None
    self._lock = threading.RLock()
    self._prompt_gate = threading.Lock()
    self._finished = threading.Event()
    self._finishing = False
    self._finalizers: list[Callable[[RunStatus], Any]] = []
    self._steps: dict[str, StepStatus] = {step.name: StepStatus.PENDING for step in self.workflow.steps}
    self._outputs: dict[str, Any] = {}
    self._summaries: dict[str, str | None] = {}  # display renderings of _outputs, computed once per output
    self._attempts: dict[str, int] = {}
    self._skip_reasons: dict[str, SkipReason] = {}
    self._produced_by: dict[str, int] = {}  # step -> attempt whose output is current (0: skipped)
    self._artifacts: dict[tuple[str, int], list[str]] = {}
    self._barrier = -1
    self._current: Step | None = None
    self._prompt: _OpenPrompt | None = None
    self._pending: _Command | None = None
    self._thread: threading.Thread | None = None
    self._loop: asyncio.AbstractEventLoop | None = None
    self._loop_thread: threading.Thread | None = None
    self._loop_stopping = False  # set once the run asks its loop to stop: the loop thread must not restart it
    self._task: asyncio.Future[Any] | None = None
    self._in_sync_call = False
    self._session_scope = contextlib.ExitStack()  # the run's binding as the process' session (see start())
    self._answers: dict[_PromptKey, tuple[Any, Any]] = {}  # identity -> (validated answer, its JSON form)
    self._kept_open = False
    self._closing: ClosingState | None = None
    self._closed = threading.Event()
    self._context: RunContext | None = None  # the latest ContextChanged (see _update_context)

kept_open property

kept_open: bool

Whether the session stays open after the run finishes (see keep_open).

closed property

closed: bool

Whether the finished run's session was closed (see close).

start

start() -> None

Starts executing the workflow on a background thread.

Source code in src/clabe/workflow/_run.py
def start(self) -> None:
    """Starts executing the workflow on a background thread."""
    with self._lock:
        if self.status is not RunStatus.CREATED:
            raise RuntimeError("A run can only be started once.")
        self.status = RunStatus.RUNNING
        context = contextvars.copy_context()
        self._thread = threading.Thread(
            target=context.run, args=(self._main,), name=f"clabe-run-{self.id}", daemon=True
        )
        # The run is the process' session (see ``clabe.ui.bind``) from here until just after RunFinished, so
        # ``ui.ask``/``ui.notify`` from steps, the code they call and their threads reach it. Bound before the
        # thread starts, so it already is when start() returns; _main unbinds it.
        self._session_scope.enter_context(ui.bind(self))
    try:
        self._thread.start()
    except BaseException:
        self._session_scope.close()
        raise

add_finalizer

add_finalizer(callback: Callable[[RunStatus], Any]) -> None

Calls callback(status) once when the run ends, before RunFinished is recorded.

For resources a run holds beyond its steps, e.g. a remote machine's lease. Callbacks run on the run thread, in the order they were added; one that raises is logged and does not stop the others.

Source code in src/clabe/workflow/_run.py
def add_finalizer(self, callback: Callable[[RunStatus], Any]) -> None:
    """Calls ``callback(status)`` once when the run ends, before ``RunFinished`` is recorded.

    For resources a run holds beyond its steps, e.g. a remote machine's lease. Callbacks run on the run thread,
    in the order they were added; one that raises is logged and does not stop the others.
    """
    with self._lock:
        self._finalizers.append(callback)

wait

wait(timeout: float | None = None) -> bool

Blocks until the run finishes; returns False if timeout elapsed first.

Source code in src/clabe/workflow/_run.py
def wait(self, timeout: float | None = None) -> bool:
    """Blocks until the run finishes; returns ``False`` if ``timeout`` elapsed first."""
    return self._finished.wait(timeout)

output

output(name: str) -> Any

Returns the output of step name (KeyError if it has not produced one).

Source code in src/clabe/workflow/_run.py
def output(self, name: str) -> Any:
    """Returns the output of step ``name`` (``KeyError`` if it has not produced one)."""
    with self._lock:
        return self._outputs[name]

ask

ask(request: Request) -> Any

Opens a prompt for request and blocks until a client answers it.

Called from step code (directly, or through clabe.ui.ask and its helpers). A FieldRequest is resolved first: the run opens the primitive prompt it resolves to (e.g. a confirm for a bool field) and returns the answer converted to the field's type.

Parameters:

Name Type Description Default
request Request

A prompt request from clabe.ui (e.g. a TextRequest).

required

Returns:

Type Description
Any

The validated, coerced answer.

Raises:

Type Description
PromptCancelledError

The prompt was cancelled (e.g. by going back or aborting). After it, return or raise; do not ask again — the run is changing course.

Source code in src/clabe/workflow/_run.py
def ask(self, request: Request) -> Any:
    """Opens a prompt for ``request`` and blocks until a client answers it.

    Called from step code (directly, or through [`clabe.ui.ask`][clabe.ui.ask] and its helpers). A [`FieldRequest`][clabe.ui.FieldRequest] is
    resolved first: the run opens the primitive prompt it resolves to (e.g. a ``confirm`` for a ``bool`` field)
    and returns the answer converted to the field's type.

    Args:
        request: A prompt request from [`clabe.ui`][clabe.ui] (e.g. a [`TextRequest`][clabe.ui.TextRequest]).

    Returns:
        The validated, coerced answer.

    Raises:
        PromptCancelledError: The prompt was cancelled (e.g. by going back or aborting). After it, return or
            raise; do not ask again — the run is changing course.
    """
    if not isinstance(request, Request):
        raise TypeError(f"Unsupported prompt request: {type(request).__name__}")
    if isinstance(request, FieldRequest):
        primitive, convert = request.resolve()
        return self._ask(primitive, None, convert)
    return self._ask(request, None)

answer

answer(
    prompt_id: str, value: Any, *, client: str = "local"
) -> Ack | Rejected

Answers the open prompt prompt_id. The first valid answer wins.

Parameters:

Name Type Description Default
prompt_id str

The prompt being answered.

required
value Any

The answer (a Python value or its JSON form).

required
client str

Who answered; recorded in the PromptClosed event.

'local'

Returns:

Type Description
Ack | Rejected

Ack if the answer closed the prompt, otherwise Rejected with the reason.

Source code in src/clabe/workflow/_run.py
def answer(self, prompt_id: str, value: Any, *, client: str = "local") -> Ack | Rejected:
    """Answers the open prompt ``prompt_id``. The first valid answer wins.

    Args:
        prompt_id: The prompt being answered.
        value: The answer (a Python value or its JSON form).
        client: Who answered; recorded in the ``PromptClosed`` event.

    Returns:
        `Ack` if the answer closed the prompt, otherwise `Rejected` with the reason.
    """
    with self._lock:
        prompt = self._prompt
    if prompt is None or prompt.id != prompt_id:
        return Rejected("This prompt is no longer open.")
    try:
        coerced = prompt.request.validate_answer(value)  # outside the lock: validators may be slow
        result = prompt.convert(coerced) if prompt.convert is not None else coerced
    except AnswerRejected as exc:
        return Rejected(str(exc))
    except Exception as exc:  # a malformed answer must never reach the client as an exception
        logger.debug("Answer %r to prompt %s broke its validator", value, prompt_id, exc_info=True)
        return Rejected(f"Invalid answer: {exc}")
    # The primitive answer is recorded (it replays the prompt), except a secret: then only its mask is.
    secret = _contains_secret(result)
    recorded = _jsonable(result if secret else coerced)  # outside the lock: may be slow
    with self._lock:
        if self._prompt is not prompt:
            return Rejected("This prompt is no longer open.")
        prompt.answer = result
        self._prompt = None
        if prompt.identity is not None:
            if secret:  # never prefilled nor forwarded
                self._answers.pop(prompt.identity, None)
            else:
                self._answers[prompt.identity] = (coerced, recorded)
        self.events.append(
            PromptClosed(prompt_id=prompt_id, outcome="answered", answered_by=client, answer=recorded)
        )
        prompt.done.set()
    return Ack()

forward

forward(*, client: str = 'local') -> Ack | Rejected

Answers the open prompt with the answer it got last time (Forward), through the normal validation.

A prompt's earlier answer is remembered per prompt identity: the step that asks it and the request's field (else its label or title, else its kind), so it is stable across attempts of the step. Secret answers and a failed step's Retry / Go back / Abort question are never remembered. The open prompt's can_forward and previous_answer (see PromptOpened) say whether and what Forward answers.

Parameters:

Name Type Description Default
client str

Who forwards; recorded in the PromptClosed event.

'local'

Returns:

Type Description
Ack | Rejected

Ack if the earlier answer closed the prompt, otherwise Rejected with the reason (no prompt is open,

Ack | Rejected

it has no earlier answer, or the answer is no longer valid).

Source code in src/clabe/workflow/_run.py
def forward(self, *, client: str = "local") -> Ack | Rejected:
    """Answers the open prompt with the answer it got last time (Forward), through the normal validation.

    A prompt's earlier answer is remembered per prompt identity: the step that asks it and the request's
    ``field`` (else its label or title, else its kind), so it is stable across attempts of the step. Secret
    answers and a failed step's Retry / Go back / Abort question are never remembered. The open prompt's
    ``can_forward`` and ``previous_answer`` (see [`PromptOpened`][clabe.workflow.events.PromptOpened]) say whether
    and what Forward answers.

    Args:
        client: Who forwards; recorded in the ``PromptClosed`` event.

    Returns:
        `Ack` if the earlier answer closed the prompt, otherwise `Rejected` with the reason (no prompt is open,
        it has no earlier answer, or the answer is no longer valid).
    """
    with self._lock:
        prompt = self._prompt
    if prompt is None:
        return Rejected("No prompt is open.")
    if not prompt.opened.can_forward:
        return Rejected("This prompt has no earlier answer to repeat.")
    return self.answer(prompt.id, prompt.previous, client=client)

previous_answer

previous_answer(prompt_id: str) -> tuple[bool, Any]

Whether the open prompt prompt_id was answered before, and that answer (the validated value).

For in-process clients that prefill the prompt (see forward); (False, None) once it closed.

Source code in src/clabe/workflow/_run.py
def previous_answer(self, prompt_id: str) -> tuple[bool, Any]:
    """Whether the open prompt ``prompt_id`` was answered before, and that answer (the validated value).

    For in-process clients that prefill the prompt (see `forward`); ``(False, None)`` once it closed.
    """
    with self._lock:
        prompt = self._prompt
        if prompt is None or prompt.id != prompt_id or not prompt.opened.can_forward:
            return False, None
        return True, prompt.previous

cancel_prompt

cancel_prompt() -> None

Cancels the open prompt, if any; the waiting step gets PromptCancelledError.

Source code in src/clabe/workflow/_run.py
def cancel_prompt(self) -> None:
    """Cancels the open prompt, if any; the waiting step gets [`PromptCancelledError`][clabe.ui.PromptCancelledError]."""
    with self._lock:
        if self._prompt is not None:
            self._cancel_prompt_locked()

prompt_request

prompt_request(prompt_id: str) -> Request | None

The request object behind an open prompt (for in-process clients), or None if it closed.

Source code in src/clabe/workflow/_run.py
def prompt_request(self, prompt_id: str) -> Request | None:
    """The request object behind an open prompt (for in-process clients), or ``None`` if it closed."""
    with self._lock:
        prompt = self._prompt
        return prompt.request if prompt is not None and prompt.id == prompt_id else None

is_prompt_open

is_prompt_open(prompt_id: str) -> bool

Whether prompt_id is still waiting for an answer.

Source code in src/clabe/workflow/_run.py
def is_prompt_open(self, prompt_id: str) -> bool:
    """Whether ``prompt_id`` is still waiting for an answer."""
    return self.prompt_request(prompt_id) is not None

go_back

go_back(target: str) -> Ack | Rejected

Goes back to step target: it and its dependents run again.

Rejected when target has not run, is locked by a completed barrier, or the current step is busy and cannot be interrupted (only cancellable async steps can be).

Parameters:

Name Type Description Default
target str

Name of the step to go back to.

required

Returns:

Type Description
Ack | Rejected

Ack if the command was accepted, otherwise Rejected with the reason.

Source code in src/clabe/workflow/_run.py
def go_back(self, target: str) -> Ack | Rejected:
    """Goes back to step ``target``: it and its dependents run again.

    Rejected when ``target`` has not run, is locked by a completed barrier, or the current step is busy and
    cannot be interrupted (only ``cancellable`` async steps can be).

    Args:
        target: Name of the step to go back to.

    Returns:
        `Ack` if the command was accepted, otherwise `Rejected` with the reason.
    """
    with self._lock:
        if self._finished.is_set():
            return Rejected("The run has finished.")
        if self._finishing:
            return Rejected("The run is finishing.")
        if self._aborting_locked():
            return Rejected("The run is aborting.")
        rejection = self._back_rejection(target)
        if rejection is not None:
            return Rejected(rejection)
        busy = self._current
        if self._prompt is None and busy is not None and not (busy.cancellable and self._task is not None):
            return Rejected(f"{busy.title} is busy and cannot be interrupted.")
        self._pending = _Command("back", target=target)
        self._interrupt_locked(allow_sync=False)
    return Ack()

back

back() -> Ack | Rejected

Goes back to the previous step (Back): the nearest earlier step that has run and is not locked.

The previous step of the step asking the open prompt, else of the running step; see back_target.

Returns:

Type Description
Ack | Rejected

Ack if the command was accepted, otherwise Rejected with the reason.

Source code in src/clabe/workflow/_run.py
def back(self) -> Ack | Rejected:
    """Goes back to the previous step (Back): the nearest earlier step that has run and is not locked.

    The previous step of the step asking the open prompt, else of the running step; see `back_target`.

    Returns:
        `Ack` if the command was accepted, otherwise `Rejected` with the reason.
    """
    target = self.back_target()
    if target is None:
        return Rejected("There is no earlier step to go back to.")
    return self.go_back(target)

back_target

back_target() -> str | None

The step back would go back to now, or None when Back is not available.

Source code in src/clabe/workflow/_run.py
def back_target(self) -> str | None:
    """The step `back` would go back to now, or ``None`` when Back is not available."""
    with self._lock:
        if self._finished.is_set() or self._finishing:
            return None
        name = self._prompt.opened.step if self._prompt is not None else None
        if name is None and self._current is not None:
            name = self._current.name
        if name is None or name not in self._steps:
            return None
        return self._default_back_target(self.workflow.get(name))

retry

retry(
    step: str, *, client: str = "local"
) -> Ack | Rejected

Retries step after it failed: answers its open Retry / Go back / Abort prompt with "retry".

Source code in src/clabe/workflow/_run.py
def retry(self, step: str, *, client: str = "local") -> Ack | Rejected:
    """Retries ``step`` after it failed: answers its open Retry / Go back / Abort prompt with "retry"."""
    return self._answer_step_prompt(step, f"{step}.failed", "retry", "has no failure waiting", client)

skip

skip(step: str, *, client: str = 'local') -> Ack | Rejected

Skips the optional step: answers its open "run this step?" prompt with no.

Source code in src/clabe/workflow/_run.py
def skip(self, step: str, *, client: str = "local") -> Ack | Rejected:
    """Skips the optional ``step``: answers its open "run this step?" prompt with no."""
    return self._answer_step_prompt(step, f"{step}.optional", False, "is not asking whether to run", client)

abort

abort(reason: str = 'Aborted by user.') -> Ack

Stops the run: cancels the open prompt or interrupts the busy step, then ends the run as aborted.

A busy async step is cancelled; a busy sync step gets a KeyboardInterrupt (raised when it next runs Python code, so not during a blocking native call). An async step that blocks its event loop (e.g. time.sleep inside a coroutine) cannot be cancelled until it yields. Has no effect once the run is finishing, or when an abort is already under way (the first reason is kept).

Parameters:

Name Type Description Default
reason str

Why the run was aborted; recorded as the run's reason.

'Aborted by user.'

Returns:

Type Description
Ack

Ack.

Source code in src/clabe/workflow/_run.py
def abort(self, reason: str = "Aborted by user.") -> Ack:
    """Stops the run: cancels the open prompt or interrupts the busy step, then ends the run as aborted.

    A busy async step is cancelled; a busy sync step gets a ``KeyboardInterrupt`` (raised when it next runs
    Python code, so not during a blocking native call). An async step that blocks its event loop (e.g.
    ``time.sleep`` inside a coroutine) cannot be cancelled until it yields. Has no effect once the run is
    finishing, or when an abort is already under way (the first reason is kept).

    Args:
        reason: Why the run was aborted; recorded as the run's reason.

    Returns:
        `Ack`.
    """
    with self._lock:
        if not (self._finished.is_set() or self._finishing or self._aborting_locked()):
            self._pending = _Command("abort", reason=reason)
            self._interrupt_locked(allow_sync=True)  # once per run: a second abort is a no-op
    return Ack()

keep_open

keep_open() -> None

Keeps the run's session open after it finishes, until close (or the launcher) ends it.

Called before the run starts by whoever shows a closing screen (the launcher, when the run is served). Event streams of a run kept open end with RunClosed instead of RunFinished.

Source code in src/clabe/workflow/_run.py
def keep_open(self) -> None:
    """Keeps the run's session open after it finishes, until `close` (or the launcher) ends it.

    Called before the run starts by whoever shows a closing screen (the launcher, when the run is served). Event
    streams of a run kept open end with ``RunClosed`` instead of ``RunFinished``.
    """
    with self._lock:
        self._kept_open = True

begin_closing

begin_closing(deadline: datetime | None = None) -> None

Shows the closing screen: records RunClosing and exposes it in state (closing).

Does nothing if the screen is already shown, or if a client closed the session first.

Parameters:

Name Type Description Default
deadline datetime | None

When the session closes on its own; None waits for a client.

None
Source code in src/clabe/workflow/_run.py
def begin_closing(self, deadline: datetime.datetime | None = None) -> None:
    """Shows the closing screen: records ``RunClosing`` and exposes it in `state` (``closing``).

    Does nothing if the screen is already shown, or if a client closed the session first.

    Args:
        deadline: When the session closes on its own; ``None`` waits for a client.
    """
    with self._lock:
        if self._closing is not None:
            return
        self._closing = ClosingState(since=datetime.datetime.now(datetime.UTC), deadline=deadline)
        self.events.append(RunClosing(deadline=deadline))

close

close(*, client: str = 'local') -> Ack | Rejected

Closes the finished run's session (the closing screen's Close button). The first close wins.

Accepted once the run has finished, if its session is kept open (see keep_open) or shows a closing screen.

Parameters:

Name Type Description Default
client str

Who closed; recorded in the RunClosed event ("timeout" when the deadline passed).

'local'

Returns:

Type Description
Ack | Rejected

Ack once the session is closed by this call, otherwise Rejected (the run has not finished, its

Ack | Rejected

session is not kept open, or it is already closed).

Source code in src/clabe/workflow/_run.py
def close(self, *, client: str = "local") -> Ack | Rejected:
    """Closes the finished run's session (the closing screen's Close button). The first close wins.

    Accepted once the run has finished, if its session is kept open (see `keep_open`) or shows a closing screen.

    Args:
        client: Who closed; recorded in the ``RunClosed`` event (``"timeout"`` when the deadline passed).

    Returns:
        `Ack` once the session is closed by this call, otherwise `Rejected` (the run has not finished, its
        session is not kept open, or it is already closed).
    """
    with self._lock:
        if not self._finished.is_set():
            return Rejected("The run has not finished.")
        if not self._kept_open and self._closing is None:
            return Rejected("This run has no closing screen.")
        if self._closed.is_set():
            return Rejected("The session is already closed.")
        if self._closing is None:
            self._closing = ClosingState(since=datetime.datetime.now(datetime.UTC))
        self._closing.closed, self._closing.closed_by = True, client
        self.events.append(RunClosed(closed_by=client))
        self._closed.set()
    return Ack()

wait_closed

wait_closed(timeout: float | None = None) -> bool

Blocks until the session is closed (see close); returns False if timeout elapsed first.

Source code in src/clabe/workflow/_run.py
def wait_closed(self, timeout: float | None = None) -> bool:
    """Blocks until the session is closed (see `close`); returns ``False`` if ``timeout`` elapsed first."""
    return self._closed.wait(timeout)

notify

notify(message: str, level: MessageLevel = INFO) -> None

Records a message for the user.

Parameters:

Name Type Description Default
message str

The text to show.

required
level MessageLevel

How prominently to show it.

INFO
Source code in src/clabe/workflow/_run.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Records a message for the user.

    Args:
        message: The text to show.
        level: How prominently to show it.
    """
    with self._lock:
        self.events.append(Notify(message=message, level=level.value))

header

header(text: str) -> None

Records a header for the user.

Parameters:

Name Type Description Default
text str

The header text.

required
Source code in src/clabe/workflow/_run.py
def header(self, text: str) -> None:
    """Records a header for the user.

    Args:
        text: The header text.
    """
    with self._lock:
        self.events.append(Header(text=text))

activity

activity(
    description: str, *, machine: str | None = None
) -> Generator[str, None, None]

Records live work (e.g. a running app) as start/end events around the block.

The run observes the process-wide activity indicator while it executes, so it records activities from any thread: each is attributed to the step running when it starts (step=None outside a step), and two concurrent runs in one process would record each other's activities (one run per process is supported).

Parameters:

Name Type Description Default
description str

What the work is, as shown to the user.

required
machine str | None

The machine the work runs on, when not this one.

None

Yields:

Type Description
str

The activity's id, to record its output with activity_output.

Source code in src/clabe/workflow/_run.py
@contextlib.contextmanager
def activity(self, description: str, *, machine: str | None = None) -> Generator[str, None, None]:
    """Records live work (e.g. a running app) as start/end events around the block.

    The run observes the process-wide activity indicator while it executes, so it records activities from any
    thread: each is attributed to the step running when it starts (``step=None`` outside a step), and two
    concurrent runs in one process would record each other's activities (one run per process is supported).

    Args:
        description: What the work is, as shown to the user.
        machine: The machine the work runs on, when not this one.

    Yields:
        The activity's id, to record its output with `activity_output`.
    """
    activity_id = uuid.uuid4().hex[:12]
    with self._lock:  # the step read and the event are one atomic change: no step can start or end between
        step = self._current.name if self._current is not None else None
        self.events.append(
            ActivityStarted(activity_id=activity_id, description=description, step=step, machine=machine)
        )
    try:
        yield activity_id
    finally:
        # Not under _lock (no state is read): an abort's KeyboardInterrupt could land on acquiring it and the
        # activity would never end. The event log is thread-safe on its own.
        self.events.append(ActivityEnded(activity_id=activity_id))

activity_output

activity_output(activity_id: str, lines: list[str]) -> None

Records new output lines of a running activity.

Source code in src/clabe/workflow/_run.py
def activity_output(self, activity_id: str, lines: list[str]) -> None:
    """Records new output lines of a running activity."""
    if lines:
        self.events.append(ActivityOutput(activity_id=activity_id, lines=lines))

state

state() -> RunState

A consistent snapshot of the run; clients then follow events after last_seq.

Returns:

Type Description
RunState

The run's status, its steps, the open prompt (if any) and the sequence number of the latest event the

RunState

snapshot reflects.

Source code in src/clabe/workflow/_run.py
def state(self) -> RunState:
    """A consistent snapshot of the run; clients then follow events after ``last_seq``.

    Returns:
        The run's status, its steps, the open prompt (if any) and the sequence number of the latest event the
        snapshot reflects.
    """
    with self._lock:
        steps = [
            StepState(
                name=step.name,
                title=step.title,
                status=self._steps[step.name],
                barrier=step.barrier,
                optional=step.optional,
                locked=index <= self._barrier,
                summary=self._summaries.get(step.name),
                conditional=step.when is not None,
                skip_reason=self._skip_reasons.get(step.name),
            )
            for index, step in enumerate(self.workflow.steps)
        ]
        return RunState(
            run_id=self.id,
            workflow=self.workflow.name,
            status=self.status,
            current_step=self._current.name if self._current is not None else None,
            steps=steps,
            prompt=self._prompt.opened if self._prompt is not None else None,
            last_seq=self.events.last_seq,
            back_target=self.back_target(),
            closing=self._closing.model_copy() if self._closing is not None else None,
            context=self._context.model_copy() if self._context is not None else None,
        )

RunState

Bases: BaseModel

Snapshot of a run, for clients attaching mid-run. Follow events after last_seq.

back_target is the step Run.back would go back to (None: Back is not available). closing is set once the finished run shows its closing screen. context is what the run is about so far (the latest context_changed event).

RunStatus

Bases: StrEnum

Where a run is in its lifecycle.

StepState

Bases: BaseModel

Snapshot of one step, for clients.

StepStatus

Bases: StrEnum

Where a step is in its lifecycle.

OnFailure

Bases: Flag

The choices a failed step offers (on_failure=); combine them with |.

Example
@wf.step(on_failure=OnFailure.RETRY | OnFailure.ABORT)  # no going back from here
async def acquire(...): ...

RETRY class-attribute instance-attribute

RETRY = enum.auto()

Run the step again.

GO_BACK class-attribute instance-attribute

GO_BACK = enum.auto()

Go back to the previous step that can run again (only shown when there is one).

ABORT class-attribute instance-attribute

ABORT = enum.auto()

End the run.

ALL class-attribute instance-attribute

ALL = RETRY | GO_BACK | ABORT

Every choice (the default).

Step dataclass

Step(
    name: str,
    func: Callable[..., Any],
    title: str,
    params: tuple[str, ...],
    barrier: bool = False,
    on_error: OnError = "raise",
    optional: str | None = None,
    undo: Callable[[Any], Any] | None = None,
    cancellable: bool = False,
    codec: Codec | None = None,
    when: Callable[..., Any] | None = None,
    when_params: tuple[str, ...] = (),
    optional_default: bool = True,
    on_failure: OnFailure = ALL,
)

One declared step of a Workflow.

Attributes:

Name Type Description
name str

Unique name; the step's return value is stored under it.

func Callable[..., Any]

The step function (sync or async).

title str

Human-readable title shown by frontends.

params tuple[str, ...]

The function's parameter names, resolved by name when the step runs.

barrier bool

Once completed, neither this step nor any before it can run again.

on_error OnError

"raise" pauses the run with Retry/Go back/Abort; "warn" notifies and continues with None as the step's output.

on_failure OnFailure

Which of Retry / Go back / Abort a failure offers (OnFailure; all by default). Aborting from the menu or with Ctrl+C always works.

optional str | None

When set, the run asks this question first and skips the step on "no".

optional_default bool

The answer the optional question suggests (True: run the step).

when Callable[..., Any] | None

A condition on earlier outputs (taken by parameter name, like a step's inputs): the step runs only when it returns something true, and is skipped otherwise. Going back to a step it reads evaluates it again.

when_params tuple[str, ...]

The condition's parameter names.

undo Callable[[Any], Any] | None

Called with the step's output when a completed step is invalidated by going back.

cancellable bool

An async step that may be interrupted by going back while it is busy.

codec Codec | None

How the output is recorded in outputs.jsonl (see clabe.workflow.codecs); None uses codecs.auto.

deps property

deps: tuple[str, ...]

What must be produced by earlier steps: the step's inputs, then its condition's (without repeats).

options

options() -> dict[str, Any]

The declaration options, as accepted by Workflow.step.

Source code in src/clabe/workflow/_workflow.py
def options(self) -> dict[str, Any]:
    """The declaration options, as accepted by `Workflow.step`."""
    return {
        "title": self.title,
        "barrier": self.barrier,
        "on_error": self.on_error,
        "optional": self.optional,
        "optional_default": self.optional_default,
        "undo": self.undo,
        "cancellable": self.cancellable,
        "codec": self.codec,
        "when": self.when,
        "on_failure": self.on_failure,
    }

Workflow

Workflow(
    name: str,
    *,
    order: int = 0,
    exit_prompt_timeout: float | None = None,
)

An ordered list of steps. Declaration order is the stepper order.

Example
wf = Workflow("vr-foraging", exit_prompt_timeout=60)

@wf.step
def session(launcher) -> Session: ...

@wf.step(barrier=True)
def register(launcher, session) -> None: ...

Step outputs are passed to later steps by reference: a step must not mutate what it receives — return a new value instead (e.g. session.model_copy(update=...)).

Parameters:

Name Type Description Default
name str

Human-readable name of the workflow (what clabe run lists).

required
order int

Sort key when a module defines several workflows (lower first).

0
exit_prompt_timeout float | None

Seconds the launcher waits at its exit prompt; None waits, 0 skips it (after a successful run only: after a failure or abort it waits).

None
Source code in src/clabe/workflow/_workflow.py
def __init__(self, name: str, *, order: int = 0, exit_prompt_timeout: float | None = None) -> None:
    if exit_prompt_timeout is not None and exit_prompt_timeout < 0:
        raise ValueError(f"exit_prompt_timeout must be None or >= 0, got {exit_prompt_timeout}.")
    self.name = name
    self.order = order
    self.exit_prompt_timeout = exit_prompt_timeout
    self._steps: tuple[Step, ...] = ()

steps property

steps: tuple[Step, ...]

The declared steps, in order.

step

step(
    func: Callable[..., Any] | Step | None = None,
    /,
    **options: Any,
) -> Any

Declares a step. Use as @wf.step or @wf.step(title=..., barrier=True, ...).

The decorated function is returned unchanged, so steps stay testable as plain functions. Every parameter must name an earlier step or a built-in (launcher, run), even one with a default value: a misspelled input fails here rather than silently falling back to its default. See Step for the options.

To reuse a step of another workflow with its name and options, pass it: wf.step(vr.get("qc")), or wf.step(vr.get("qc"), optional=None) to change some. insert_before, insert_after and replace take a Step too.

Source code in src/clabe/workflow/_workflow.py
def step(self, func: "Callable[..., Any] | Step | None" = None, /, **options: Any) -> Any:
    """Declares a step. Use as ``@wf.step`` or ``@wf.step(title=..., barrier=True, ...)``.

    The decorated function is returned unchanged, so steps stay testable as plain functions.
    Every parameter must name an earlier step or a built-in (``launcher``, ``run``), even one with a
    default value: a misspelled input fails here rather than silently falling back to its default.
    See `Step` for the options.

    To reuse a step of another workflow with its name and options, pass it: ``wf.step(vr.get("qc"))``, or
    ``wf.step(vr.get("qc"), optional=None)`` to change some. `insert_before`, `insert_after` and `replace` take
    a `Step` too.
    """

    def register(f: Callable[..., Any]) -> Callable[..., Any]:
        self._set_steps([*self._steps, make_step(f, **options)])
        return f

    return register if func is None else register(func)

get

get(name: str) -> Step

Returns the step called name.

Source code in src/clabe/workflow/_workflow.py
def get(self, name: str) -> Step:
    """Returns the step called ``name``."""
    for step in self._steps:
        if step.name == name:
            return step
    raise KeyError(f"No step named {name!r} in workflow {self.name!r}.")

step_named_by

step_named_by(
    target: str | Callable[..., Any] | Step | None,
) -> tuple[str | None, str | None]

The name of the step target designates (a name, a step, or a step's function, found by identity), and why none could be found (None when found). A name or None is returned as is.

Source code in src/clabe/workflow/_workflow.py
def step_named_by(self, target: "str | Callable[..., Any] | Step | None") -> tuple[str | None, str | None]:
    """The name of the step ``target`` designates (a name, a step, or a step's function, found by identity),
    and why none could be found (``None`` when found). A name or ``None`` is returned as is."""
    if target is None or isinstance(target, str):
        return target, None
    if isinstance(target, Step):
        target = target.func
    names = [step.name for step in self._steps if step.func is target]
    what = getattr(target, "__name__", repr(target))
    if not names:
        return None, f"Cannot go back to {what}: it is not a step of {self.name!r}."
    if len(names) > 1:
        return None, f"Cannot go back to {what}: steps {', '.join(map(repr, names))} run it; give a name."
    return names[0], None

index

index(name: str) -> int

Returns the position of the step called name.

Source code in src/clabe/workflow/_workflow.py
def index(self, name: str) -> int:
    """Returns the position of the step called ``name``."""
    return self._steps.index(self.get(name))

dependents

dependents(name: str) -> list[str]

Names of the steps that transitively depend on name, in declaration order.

Source code in src/clabe/workflow/_workflow.py
def dependents(self, name: str) -> list[str]:
    """Names of the steps that transitively depend on ``name``, in declaration order."""
    affected = {name}
    result = []
    for step in self._steps[self.index(name) + 1 :]:
        if affected.intersection(step.deps):
            affected.add(step.name)
            result.append(step.name)
    return result

variant

variant(
    name: str,
    *,
    order: int | None = None,
    exit_prompt_timeout: float | None | EllipsisType = ...,
) -> Workflow

Returns a copy named name with the same steps, to customise further.

Parameters:

Name Type Description Default
name str

The copy's name.

required
order int | None

The copy's order; this workflow's by default.

None
exit_prompt_timeout float | None | EllipsisType

The copy's exit_prompt_timeout (None included); this workflow's by default.

...
Source code in src/clabe/workflow/_workflow.py
def variant(
    self, name: str, *, order: int | None = None, exit_prompt_timeout: float | None | EllipsisType = ...
) -> "Workflow":
    """Returns a copy named ``name`` with the same steps, to customise further.

    Args:
        name: The copy's name.
        order: The copy's ``order``; this workflow's by default.
        exit_prompt_timeout: The copy's ``exit_prompt_timeout`` (``None`` included); this workflow's by default.
    """
    copy = Workflow(
        name,
        order=self.order if order is None else order,
        exit_prompt_timeout=self.exit_prompt_timeout if exit_prompt_timeout is ... else exit_prompt_timeout,
    )
    copy._steps = self._steps
    return copy

concatenate

concatenate(
    other: Workflow, *, name: str | None = None
) -> Workflow

Returns a new workflow: this one's steps, then other's (both stay unchanged).

other is a complete workflow, so its steps only take its own outputs and the built-ins (launcher, run): nothing passes from this workflow's steps to other's. Use it for blocks every experiment shares, e.g. a data hand-off at the end. The new workflow keeps this one's order and exit_prompt_timeout.

Parameters:

Name Type Description Default
other Workflow

The workflow whose steps come after this one's.

required
name str | None

The new workflow's name; this one's by default.

None

Raises:

Type Description
WorkflowDefinitionError

A step name is in both workflows.

Source code in src/clabe/workflow/_workflow.py
def concatenate(self, other: "Workflow", *, name: str | None = None) -> "Workflow":
    """Returns a new workflow: this one's steps, then ``other``'s (both stay unchanged).

    ``other`` is a complete workflow, so its steps only take its own outputs and the built-ins (``launcher``,
    ``run``): nothing passes from this workflow's steps to ``other``'s. Use it for blocks every experiment shares,
    e.g. a data hand-off at the end. The new workflow keeps this one's ``order`` and ``exit_prompt_timeout``.

    Args:
        other: The workflow whose steps come after this one's.
        name: The new workflow's name; this one's by default.

    Raises:
        WorkflowDefinitionError: A step name is in both workflows.
    """
    shared = sorted({s.name for s in self._steps} & {s.name for s in other.steps})
    if shared:
        raise WorkflowDefinitionError(
            f"Cannot concatenate {other.name!r} after {self.name!r}: both have step(s) {', '.join(map(repr, shared))}."
        )
    combined = Workflow(name or self.name, order=self.order, exit_prompt_timeout=self.exit_prompt_timeout)
    combined._set_steps([*self._steps, *other.steps])
    return combined

insert_before

insert_before(
    anchor: str,
    func: Callable[..., Any] | Step,
    /,
    **options: Any,
) -> Self

Inserts a new step right before anchor. See Step for the options.

Source code in src/clabe/workflow/_workflow.py
def insert_before(self, anchor: str, func: "Callable[..., Any] | Step", /, **options: Any) -> Self:
    """Inserts a new step right before ``anchor``. See `Step` for the options."""
    steps = list(self._steps)
    steps.insert(self.index(anchor), make_step(func, **options))
    self._set_steps(steps)
    return self

insert_after

insert_after(
    anchor: str,
    func: Callable[..., Any] | Step,
    /,
    **options: Any,
) -> Self

Inserts a new step right after anchor. See Step for the options.

Source code in src/clabe/workflow/_workflow.py
def insert_after(self, anchor: str, func: "Callable[..., Any] | Step", /, **options: Any) -> Self:
    """Inserts a new step right after ``anchor``. See `Step` for the options."""
    steps = list(self._steps)
    steps.insert(self.index(anchor) + 1, make_step(func, **options))
    self._set_steps(steps)
    return self

replace

replace(
    name: str,
    func: Callable[..., Any] | Step,
    /,
    **options: Any,
) -> Self

Replaces step name with func, keeping its name and (unless overridden) its options.

Inherited options (notably undo, codec, cancellable) describe the old function; override them if the new one differs. A Step of another workflow brings its own options instead (its name becomes name).

Source code in src/clabe/workflow/_workflow.py
def replace(self, name: str, func: "Callable[..., Any] | Step", /, **options: Any) -> Self:
    """Replaces step ``name`` with ``func``, keeping its name and (unless overridden) its options.

    Inherited options (notably ``undo``, ``codec``, ``cancellable``) describe the old function; override them
    if the new one differs. A `Step` of another workflow brings its own options instead (its name becomes
    ``name``).
    """
    position = self.index(name)
    steps = list(self._steps)
    if isinstance(func, Step):  # a step of another workflow brings its own options
        steps[position] = make_step(func, **{**options, "name": name})
    else:
        steps[position] = make_step(func, name=name, **{**steps[position].options(), **options})
    self._set_steps(steps)
    return self

remove

remove(name: str) -> Self

Removes step name.

Raises:

Type Description
WorkflowDefinitionError

A later step takes its output (remove or replace that one first).

Source code in src/clabe/workflow/_workflow.py
def remove(self, name: str) -> Self:
    """Removes step ``name``.

    Raises:
        WorkflowDefinitionError: A later step takes its output (remove or replace that one first).
    """
    users = [step.name for step in self._steps if name in step.deps]
    if users:
        raise WorkflowDefinitionError(
            f"Cannot remove step {name!r}: step(s) {', '.join(map(repr, users))} take its output."
        )
    position = self.index(name)
    self._set_steps([*self._steps[:position], *self._steps[position + 1 :]])
    return self

WorkflowDefinitionError

Bases: ValueError

Raised when a workflow is declared with invalid steps or wiring.

concurrently async

concurrently(
    **branches: Callable[[], Any],
) -> dict[str, Any]

Runs branches at the same time and returns their results by name. Await it from an async step.

Each branch is a function of no arguments: an async def, a lambda returning an awaitable (lambda: app.run_async()), or a plain function (run in a worker thread). When a branch fails, the others keep going and the user picks, for that branch alone:

  • Retry it (it is called again),
  • Continue without it (its result is None), or
  • Stop all: every other branch is cancelled and BranchesStopped is raised, so the step fails and the run offers Retry / Go back / Abort for the whole step.

Aborting the run (or going back, when the step is cancellable) cancels every branch too. Cancelled branches get STOP_TIMEOUT seconds to clean up: put the shutting-down in finally (e.g. await open_ephys.close()); commands run by clabe's executors are stopped for you.

Outside a run (e.g. calling the step function in a test) nobody is asked: a failure stops all the branches and is raised.

Example
@wf.step(title="Acquire", cancellable=True)
async def acquire(launcher: Launcher, rig: Rig, session: Session) -> dict[str, Any]:
    return await concurrently(
        behavior=lambda: bonsai_app(rig, session).run_async(),
        ephys=record_ephys,  # async def: launch Open Ephys, start acquiring, close it in `finally`
    )
Source code in src/clabe/workflow/_branches.py
async def concurrently(**branches: Callable[[], Any]) -> dict[str, Any]:
    """Runs ``branches`` at the same time and returns their results by name. Await it from an async step.

    Each branch is a function of no arguments: an ``async def``, a lambda returning an awaitable
    (``lambda: app.run_async()``), or a plain function (run in a worker thread). When a branch fails, the others
    keep going and the user picks, for that branch alone:

    - **Retry** it (it is called again),
    - **Continue without** it (its result is ``None``), or
    - **Stop all**: every other branch is cancelled and `BranchesStopped` is raised, so the step fails and the
      run offers Retry / Go back / Abort for the whole step.

    Aborting the run (or going back, when the step is ``cancellable``) cancels every branch too. Cancelled branches
    get `STOP_TIMEOUT` seconds to clean up: put the shutting-down in ``finally`` (e.g.
    ``await open_ephys.close()``); commands run by clabe's executors are stopped for you.

    Outside a run (e.g. calling the step function in a test) nobody is asked: a failure stops all the branches and
    is raised.

    Example:
        ```python
        @wf.step(title="Acquire", cancellable=True)
        async def acquire(launcher: Launcher, rig: Rig, session: Session) -> dict[str, Any]:
            return await concurrently(
                behavior=lambda: bonsai_app(rig, session).run_async(),
                ephys=record_ephys,  # async def: launch Open Ephys, start acquiring, close it in `finally`
            )
        ```
    """
    if not branches:
        return {}
    context = ACTIVE_STEP.get()
    asking = asyncio.Lock()  # one failure prompt at a time
    supervisors = {
        name: asyncio.ensure_future(_supervise(name, branch, context, asking)) for name, branch in branches.items()
    }
    try:
        await asyncio.gather(*supervisors.values())
    except BaseException:
        for supervisor in supervisors.values():
            supervisor.cancel()
        await asyncio.wait(supervisors.values(), timeout=STOP_TIMEOUT)
        if any(not s.done() for s in supervisors.values()):
            logger.warning("Some branches did not stop within %ss.", STOP_TIMEOUT)
        raise
    return {name: supervisor.result() for name, supervisor in supervisors.items()}

check_path

check_path(
    path: str | Path, *, strict: bool = False
) -> list[Issue]

Checks the workflows offered by a file, or by every *.py file in a directory, without running them.

Files that import fine but offer no workflow (helper modules) are skipped; a path offering none at all is an error.

Parameters:

Name Type Description Default
path str | Path

An experiment file, or a directory of experiment files (not searched recursively).

required
strict bool

Also report unannotated or undecidable wiring as warnings.

False

Returns:

Type Description
list[Issue]

The issues found, with source set to the file concerned.

Source code in src/clabe/workflow/_check.py
def check_path(path: str | Path, *, strict: bool = False) -> list[Issue]:
    """Checks the workflows offered by a file, or by every ``*.py`` file in a directory, without running them.

    Files that import fine but offer no workflow (helper modules) are skipped; a path offering none at all is
    an error.

    Args:
        path: An experiment file, or a directory of experiment files (not searched recursively).
        strict: Also report unannotated or undecidable wiring as warnings.

    Returns:
        The issues found, with ``source`` set to the file concerned.
    """
    path = Path(path)
    if not path.exists():
        return [Issue("error", "path does not exist.", source=str(path))]
    files = sorted(p for p in path.glob("*.py") if p.name != "__init__.py") if path.is_dir() else [path]
    issues: list[Issue] = []
    found = 0
    for file in files:
        file_issues, count = _check_file(file, strict)
        issues += file_issues
        found += count
    if found == 0 and not issues:
        issues.append(Issue("error", "no workflows found.", source=str(path)))
    return issues

check_workflow

check_workflow(
    workflow: Workflow, *, strict: bool = False
) -> list[Issue]

Checks a workflow's wiring against its type annotations, without running it.

Built-in parameters (launcher, run) are never checked. Generics are compared by their origin only (list[int] fits list[str]).

Parameters:

Name Type Description Default
workflow Workflow

The workflow to check.

required
strict bool

Also report unannotated or undecidable wiring as warnings.

False

Returns:

Type Description
list[Issue]

The issues found (empty when the workflow is fine).

Source code in src/clabe/workflow/_check.py
def check_workflow(workflow: Workflow, *, strict: bool = False) -> list[Issue]:
    """Checks a workflow's wiring against its type annotations, without running it.

    Built-in parameters (``launcher``, ``run``) are never checked. Generics are compared by their origin only
    (``list[int]`` fits ``list[str]``).

    Args:
        workflow: The workflow to check.
        strict: Also report unannotated or undecidable wiring as warnings.

    Returns:
        The issues found (empty when the workflow is fine).
    """
    issues: list[Issue] = []
    declared: dict[str, Any] = {}  # each step's return annotation
    unresolved_returns: set[str] = set()  # already reported as errors; not worth a strict warning downstream
    for step in workflow.steps:

        def report(severity: Severity, message: str, step_name: str = step.name) -> None:
            issues.append(Issue(severity, message, workflow=workflow.name, step=step_name))

        inputs = tuple(d for d in step.params if d in step.deps)
        hints, errors = _resolve(step.func, (*inputs, "return"))
        # The condition's inputs are checked when annotated; a lambda's are not, and need not be.
        condition_inputs = tuple(d for d in step.when_params if d in step.deps and d not in inputs)
        if step.when is not None:
            condition_hints, condition_errors = _resolve(step.when, condition_inputs)
            hints.update(condition_hints)
            errors.update(condition_errors)
        for name, exc in errors.items():
            what = "return annotation" if name == "return" else f"annotation of {name!r}"
            report("error", f"{what} cannot be resolved ({type(exc).__name__}: {exc}).")
        if "return" in errors:
            unresolved_returns.add(step.name)
        for dep in (*inputs, *condition_inputs):
            if dep in errors or dep in unresolved_returns:
                continue
            expected, given = hints.get(dep, _UNKNOWN), declared.get(dep, _UNKNOWN)
            if given is not _UNKNOWN and _may_receive_none(workflow.get(dep), step):
                given = typing.Optional[given]  # noqa: UP045 -- a runtime value, not an annotation
            if expected is _UNKNOWN or given is _UNKNOWN:
                if strict and dep in inputs:
                    report("warning", f"cannot check {dep!r}: annotate this parameter and the return of step {dep!r}.")
                continue
            verdict = _fits(given, expected)
            if verdict is False and _fits(declared[dep], expected) is not False:
                report(
                    "error",
                    f"step {dep!r} is optional, conditional or on_error='warn', so {dep!r} may be None; "
                    f"annotate it as {_name(expected)} | None.",
                )
            elif verdict is False:
                report(
                    "error", f"parameter {dep!r} expects {_name(expected)} but step {dep!r} produces {_name(given)}."
                )
            elif verdict is None and strict:
                report("warning", f"cannot decide whether {_name(given)} fits {_name(expected)} for {dep!r}.")
        declared[step.name] = hints.get("return", _UNKNOWN)
    issues += _check_back_targets(workflow)
    return issues

as_workflow

as_workflow(
    target: Workflow | ExperimentCallable,
) -> Workflow

Returns target as a workflow: itself, or, for a function of the launcher, a workflow whose only step (experiment) calls it with the launcher.

Source code in src/clabe/workflow/_discovery.py
def as_workflow(target: "Workflow | ExperimentCallable") -> Workflow:
    """Returns ``target`` as a workflow: itself, or, for a function of the launcher, a workflow whose only step
    (``experiment``) calls it with the launcher."""
    if isinstance(target, Workflow):
        return target
    workflow = Workflow(getattr(target, "__name__", None) or "experiment")

    def experiment_step(launcher: "Launcher") -> Any:
        return target(launcher)

    workflow.step(experiment_step, name="experiment", title=workflow.name)
    # Set after declaring the step: inspect.signature follows __wrapped__, and the step's parameter is `launcher`.
    experiment_step.__wrapped__ = target  # type: ignore[attr-defined]  # provenance points at the real function
    return workflow

collect_workflows

collect_workflows(module: ModuleType) -> list[Workflow]

The workflows a module offers (its Workflow objects), sorted by order.

Ties keep declaration order. A workflow bound to several names is listed once.

Source code in src/clabe/workflow/_discovery.py
def collect_workflows(module: ModuleType) -> list[Workflow]:
    """The workflows a module offers (its ``Workflow`` objects), sorted by ``order``.

    Ties keep declaration order. A workflow bound to several names is listed once.
    """
    found: list[Workflow] = []
    for value in vars(module).values():
        if isinstance(value, Workflow) and not any(value is seen for seen in found):
            found.append(value)
    return sorted(found, key=lambda workflow: workflow.order)

list_experiments

list_experiments(path: str | Path) -> ExperimentListing

Lists the workflows offered by a file, or by every *.py file in a directory (not recursively).

Files that fail to import are reported in errors; nothing runs except the files' imports.

Source code in src/clabe/workflow/_discovery.py
def list_experiments(path: str | Path) -> ExperimentListing:
    """Lists the workflows offered by a file, or by every ``*.py`` file in a directory (not recursively).

    Files that fail to import are reported in ``errors``; nothing runs except the files' imports.
    """
    path = Path(path)
    files = sorted(p for p in path.glob("*.py") if p.name != "__init__.py") if path.is_dir() else [path]
    experiments, errors = [], []
    for file in files:
        try:
            module = load_module(file)
        except Exception as exc:  # noqa: BLE001 -- any import failure is reported, not raised
            errors.append(ListingError(file=str(file), error=f"{type(exc).__name__}: {exc}"))
            continue
        for workflow in collect_workflows(module):
            steps = [
                StepInfo(
                    name=s.name,
                    title=s.title,
                    barrier=s.barrier,
                    optional=s.optional,
                    conditional=s.when is not None,
                )
                for s in workflow.steps
            ]
            experiments.append(ExperimentInfo(file=str(file), name=workflow.name, steps=steps))
    return ExperimentListing(experiments=experiments, errors=errors)

load_module

load_module(path: Path) -> ModuleType

Imports the Python file at path; its directory is put on sys.path so sibling imports resolve.

A file inside a package (a folder with an __init__.py) is imported as a module of that package, so its relative imports resolve: the folder above the outermost package is put on sys.path instead.

Source code in src/clabe/workflow/_discovery.py
def load_module(path: Path) -> ModuleType:
    """Imports the Python file at ``path``; its directory is put on ``sys.path`` so sibling imports resolve.

    A file inside a package (a folder with an ``__init__.py``) is imported as a module of that package, so its relative
    imports resolve: the folder above the outermost package is put on ``sys.path`` instead.
    """
    path = Path(path).resolve()
    package = path.parent
    parts = [path.stem]
    while (package / "__init__.py").is_file():
        parts.insert(0, package.name)
        package = package.parent
    if len(parts) > 1:
        if str(package) not in sys.path:
            sys.path.insert(0, str(package))
        return importlib.import_module(".".join(parts))
    script_dir = str(path.parent)
    if script_dir not in sys.path:
        sys.path.insert(0, script_dir)
    spec = importlib.util.spec_from_file_location(path.stem, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Cannot load module from {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[path.stem] = module
    spec.loader.exec_module(module)
    return module

select_workflow

select_workflow(
    path: Path, *, name: str | None = None
) -> Workflow

Loads path and returns one of its workflows.

name selects directly; a single workflow is returned as is; otherwise the user is asked through the active clabe.ui session.

Raises:

Type Description
ValueError

If workflow names are not unique within the file.

SystemExit

If none is found, name matches nothing, or the user cancels.

Source code in src/clabe/workflow/_discovery.py
def select_workflow(path: Path, *, name: str | None = None) -> Workflow:
    """Loads ``path`` and returns one of its workflows.

    ``name`` selects directly; a single workflow is returned as is; otherwise the user is asked through the active
    [`clabe.ui`][clabe.ui] session.

    Raises:
        ValueError: If workflow names are not unique within the file.
        SystemExit: If none is found, ``name`` matches nothing, or the user cancels.
    """
    workflows = collect_workflows(load_module(path))
    by_name = {workflow.name: workflow for workflow in workflows}
    if len(by_name) != len(workflows):
        raise ValueError(f"Workflow names must be unique within {path}.")
    if not workflows:
        raise SystemExit(f"No workflows found in {path}")
    if name is not None:
        if name not in by_name:
            raise SystemExit(f"No experiment named '{name}' in {path}. Available: {', '.join(by_name)}")
        selected = by_name[name]
    elif len(workflows) == 1:
        selected = workflows[0]
    else:
        choice = ui.pick("Select experiment to run", list(by_name), allow_none=False, field="experiment")
        if choice is None:
            raise SystemExit("No experiment selected; exiting.")
        selected = by_name[choice]
    logger.info("Selected experiment: %s", selected.name)
    return selected

export_artifact

export_artifact(
    source: PathLike[str] | bytes | str | BaseModel,
    name: str | None = None,
) -> Path

Saves a file into the current step's artifacts and records it with the step's output.

Only valid inside a running step (including code the step calls on the same thread or in its tasks, and the step's codec). Code on a new threading.Thread does not see the step; asyncio.to_thread does. Artifacts land in <record_dir>/artifacts/<step>/<attempt>/<name>.

Parameters:

Name Type Description Default
source PathLike[str] | bytes | str | BaseModel

A Path to copy (file or directory), bytes, str (text content — use a Path to copy a file) or a pydantic model (saved as JSON).

required
name str | None

Name under the step's artifacts, may include sub-folders. Defaults to the file name of a Path.

None

Returns:

Type Description
Path

The absolute path of the saved artifact.

Raises:

Type Description
RuntimeError

Called outside a running step, or the run keeps no records.

ValueError

Missing or unsafe name.

FileExistsError

name was already exported by this step attempt.

TypeError

source is of an unsupported type.

Source code in src/clabe/workflow/_records.py
def export_artifact(source: "os.PathLike[str] | bytes | str | BaseModel", name: str | None = None) -> Path:
    """Saves a file into the current step's artifacts and records it with the step's output.

    Only valid inside a running step (including code the step calls on the same thread or in its tasks, and the
    step's codec). Code on a new ``threading.Thread`` does not see the step; ``asyncio.to_thread`` does.
    Artifacts land in ``<record_dir>/artifacts/<step>/<attempt>/<name>``.

    Args:
        source: A ``Path`` to copy (file or directory), ``bytes``, ``str`` (text content — use a ``Path`` to copy
            a file) or a pydantic model (saved as JSON).
        name: Name under the step's artifacts, may include sub-folders. Defaults to the file name of a ``Path``.

    Returns:
        The absolute path of the saved artifact.

    Raises:
        RuntimeError: Called outside a running step, or the run keeps no records.
        ValueError: Missing or unsafe ``name``.
        FileExistsError: ``name`` was already exported by this step attempt.
        TypeError: ``source`` is of an unsupported type.
    """
    context = ACTIVE_STEP.get()
    if context is None:
        raise RuntimeError("export_artifact() can only be called from inside a running step.")
    return context.run._export_artifact(context.step, context.attempt, source, name)

step_defaults

step_defaults(**options: Any) -> Callable[[_F], _F]

Gives a step function default options, e.g. a reusable step that should be a barrier.

Options passed when the step is declared (wf.step(func, barrier=False)) override these. See Step for the options.

Source code in src/clabe/workflow/_workflow.py
def step_defaults(**options: Any) -> Callable[[_F], _F]:
    """Gives a step function default options, e.g. a reusable step that should be a barrier.

    Options passed when the step is declared (``wf.step(func, barrier=False)``) override these. See `Step`
    for the options.
    """

    def mark(func: _F) -> _F:
        setattr(func, STEP_DEFAULTS, dict(options))
        return func

    return mark