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
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
|
|
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 |
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.
GoBack ¶
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 ( |
None
|
Source code in src/clabe/workflow/_control.py
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 ¶
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
drive ¶
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
report ¶
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
ReplayClient ¶
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 |
required |
Source code in src/clabe/workflow/_replay.py
ask ¶
The next recorded answer, after checking it answered the same question.
Source code in src/clabe/workflow/_replay.py
cancel ¶
notify ¶
notify(message: str, level: MessageLevel = INFO) -> None
ReplayMismatch ¶
Bases: RuntimeError
The run asked something the recorded session did not answer at that point.
ClosingState ¶
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 ( |
required |
launcher
|
Launcher | None
|
Passed to steps that take a |
None
|
record_dir
|
Path | None
|
When given, the run's records are written there: |
None
|
run_id
|
str | None
|
Identifier of the run; generated when omitted. |
None
|
Source code in src/clabe/workflow/_run.py
kept_open
property
¶
kept_open: bool
Whether the session stays open after the run finishes (see keep_open).
start ¶
Starts executing the workflow on a background thread.
Source code in src/clabe/workflow/_run.py
add_finalizer ¶
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
wait ¶
output ¶
ask ¶
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 |
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
answer ¶
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 |
'local'
|
Returns:
| Type | Description |
|---|---|
Ack | Rejected
|
|
Source code in src/clabe/workflow/_run.py
forward ¶
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 |
'local'
|
Returns:
| Type | Description |
|---|---|
Ack | Rejected
|
|
Ack | Rejected
|
it has no earlier answer, or the answer is no longer valid). |
Source code in src/clabe/workflow/_run.py
previous_answer ¶
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
cancel_prompt ¶
Cancels the open prompt, if any; the waiting step gets PromptCancelledError.
prompt_request ¶
The request object behind an open prompt (for in-process clients), or None if it closed.
Source code in src/clabe/workflow/_run.py
is_prompt_open ¶
go_back ¶
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
|
|
Source code in src/clabe/workflow/_run.py
back ¶
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
|
|
Source code in src/clabe/workflow/_run.py
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
retry ¶
Retries step after it failed: answers its open Retry / Go back / Abort prompt with "retry".
Source code in src/clabe/workflow/_run.py
skip ¶
Skips the optional step: answers its open "run this step?" prompt with no.
Source code in src/clabe/workflow/_run.py
abort ¶
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
|
|
Source code in src/clabe/workflow/_run.py
keep_open ¶
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
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
|
Source code in src/clabe/workflow/_run.py
close ¶
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 |
'local'
|
Returns:
| Type | Description |
|---|---|
Ack | Rejected
|
|
Ack | Rejected
|
session is not kept open, or it is already closed). |
Source code in src/clabe/workflow/_run.py
wait_closed ¶
Blocks until the session is closed (see close); returns False if timeout elapsed first.
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
header ¶
header(text: str) -> None
Records a header for the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The header text. |
required |
activity ¶
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 |
Source code in src/clabe/workflow/_run.py
activity_output ¶
Records new output lines of a running activity.
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
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).
StepState ¶
Bases: BaseModel
Snapshot of one step, for clients.
OnFailure ¶
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
|
|
on_failure |
OnFailure
|
Which of Retry / Go back / Abort a failure offers ( |
optional |
str | None
|
When set, the run asks this question first and skips the step on "no". |
optional_default |
bool
|
The answer the |
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 |
deps
property
¶
What must be produced by earlier steps: the step's inputs, then its condition's (without repeats).
options ¶
The declaration options, as accepted by Workflow.step.
Source code in src/clabe/workflow/_workflow.py
Workflow ¶
An ordered list of steps. Declaration order is the stepper order.
Example
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 |
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
|
Source code in src/clabe/workflow/_workflow.py
step ¶
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
get ¶
Returns the step called name.
step_named_by ¶
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
index ¶
dependents ¶
Names of the steps that transitively depend on name, in declaration order.
Source code in src/clabe/workflow/_workflow.py
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 |
None
|
exit_prompt_timeout
|
float | None | EllipsisType
|
The copy's |
...
|
Source code in src/clabe/workflow/_workflow.py
concatenate ¶
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
insert_before ¶
Inserts a new step right before anchor. See Step for the options.
Source code in src/clabe/workflow/_workflow.py
insert_after ¶
Inserts a new step right after anchor. See Step for the options.
Source code in src/clabe/workflow/_workflow.py
replace ¶
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
remove ¶
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
WorkflowDefinitionError ¶
Bases: ValueError
Raised when a workflow is declared with invalid steps or wiring.
concurrently
async
¶
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
BranchesStoppedis 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
check_path ¶
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 code in src/clabe/workflow/_check.py
check_workflow ¶
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
as_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
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
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
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
select_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, |
Source code in src/clabe/workflow/_discovery.py
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 |
required |
name
|
str | None
|
Name under the step's artifacts, may include sub-folders. Defaults to the file name of a |
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 |
FileExistsError
|
|
TypeError
|
|
Source code in src/clabe/workflow/_records.py
step_defaults ¶
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.