Skip to content

clabe.launcher

Launcher

Launcher(
    *,
    settings: LauncherCliArgs,
    attached_logger: Logger | None = None,
    client: Client | None = None,
)

Base class for experiment launchers. Provides functionality for managing configuration files, directories, and experiment execution.

This class serves as the foundation for launcher implementations, providing session management, directory handling, validation, and lifecycle management.

Properties

logger: The logger instance used by the launcher settings: The launcher configuration settings session: The registered session model session_directory: The path to the session directory

Methods:

Name Description
register_session

Registers a session model with the launcher

run_experiment

Main entry point for launcher execution

copy_logs

Closes file handlers and copies temporary data

make_header

Creates a formatted header string for the launcher

validate

Validates dependencies required for the launcher

save_temp_model

Saves a temporary JSON representation of a schema model

create_directory

Creates a directory at the specified path

Initializes the Launcher instance.

Parameters:

Name Type Description Default
settings LauncherCliArgs

The settings for the launcher

required
attached_logger Logger | None

An attached logger instance. Defaults to None

None
client Client | None

The user interface (console, TUI, ...). Defaults to the backend selected by settings.frontend

None
Source code in src/clabe/launcher/_base.py
def __init__(
    self,
    *,
    settings: LauncherCliArgs,
    attached_logger: logging.Logger | None = None,
    client: Client | None = None,
) -> None:
    """
    Initializes the Launcher instance.

    Args:
        settings: The settings for the launcher
        attached_logger: An attached logger instance. Defaults to None
        client: The user interface (console, TUI, ...). Defaults to the backend selected by
            ``settings.frontend``
    """
    self._settings = settings
    # Outside a run, library code asks and informs the user through the launcher's client (see ``clabe.ui``);
    # a run binds itself while it executes.
    self._ui_session = ClientSession(client or make_client(settings.frontend))
    self._ui_binding = ui.bind(self._ui_session)
    self._ui_binding.__enter__()
    self.temp_dir = Path(TMP_DIR) / format_datetime(utcnow())
    self.computer_name = os.environ.get("COMPUTERNAME") or socket.gethostname()
    self._data_directory: Path | None = None
    repository_dir = (
        Path(self.settings.repository_directory) if self.settings.repository_directory is not None else None
    )
    self.repository = GitRepository() if repository_dir is None else GitRepository(path=repository_dir)

    self._ensure_directory_structure()

    # Solve logger.
    if attached_logger:
        _logger = clabe_logging.add_file_handler(attached_logger, self.temp_dir / "launcher.log")
    else:
        root_logger = logging.getLogger()
        _logger = clabe_logging.add_file_handler(root_logger, self.temp_dir / "launcher.log")

    # Map verbosity flags to the console log level; debug mode also times every runnable's notification.
    set_include_timing(settings.debug_mode)
    if settings.debug_mode:
        display_level = logging.DEBUG
    elif settings.verbose:
        display_level = logging.INFO
    elif settings.quiet:
        display_level = logging.ERROR
    else:
        display_level = logging.WARNING

    _logger.setLevel(logging.DEBUG if settings.debug_mode else logging.INFO)
    clabe_logging.set_console_level(display_level)

    self._logger = _logger

    self._session: Session | None = None
    self._extra_session_directories: list[Path] = []  # see add_session_directory
    self._has_copied_logs = False
    self._manifest: RunManifest | None = None
    self._manifest_lock = threading.Lock()
    self._has_run = False
    self._serving = contextlib.ExitStack()  # the run server, kept up until the launcher exits (see _exit)
    self._served_run: Run | None = None
    self._last_run: Run | None = None  # the run an issue report from the exit prompt is about

client property writable

client: Client

The user interface this launcher asks and informs through outside a run (and drives the run with).

data_directory property

data_directory: Path

Returns the root data directory path.

session_directory property

session_directory: Path

Returns the session directory path.

Returns:

Name Type Description
Path Path

The session directory path

Raises:

Type Description
ValueError

If session_name is not set in the session schema

session_directories property

session_directories: list[Path | PureWindowsPath]

Every session folder of this run: this machine's, then its others, then every other machine's through its network share.

  • This machine's other folders are the ones added with add_session_directory, in that order.
  • Another machine's folder is listed once it was registered with RemoteRepository.register_session in a step of this run.

Give it to the watchdog to upload the data of every folder: WatchdogDataTransferService(source=launcher.session_directories, ...).

Raises:

Type Description
ValueError

If session_name is not set in the session schema

session property

session: Session

Returns the registered session model.

Returns:

Name Type Description
Session Session

The session model

Raises:

Type Description
ValueError

If session is not set

manifest property

manifest: RunManifest | None

The run manifest (run.json) of the run going on, once it has started.

logger property

logger: Logger

Returns the logger instance used by the launcher.

Returns:

Type Description
Logger

logging.Logger: The logger instance

settings property

settings: LauncherCliArgs

Returns the launcher settings.

Returns:

Name Type Description
LauncherCliArgs LauncherCliArgs

The launcher settings

add_session_directory

add_session_directory(path: PathLike | str) -> Path

Adds another session folder on this machine to session_directories, e.g. where an app on this PC records to its own data folder. The folder is created if missing (an existing one, e.g. found after a crash, is fine).

It is recorded in the run's run.json (extra_session_directories). Logs are still copied to session_directory only. Adding the session folder, or a folder already added, does nothing.

Parameters:

Name Type Description Default
path PathLike | str

The folder, e.g. Path(rig.data_directory) / session.session_name.

required

Returns:

Type Description
Path

The folder, as given.

Raises:

Type Description
ValueError

If no session is registered yet.

Source code in src/clabe/launcher/_base.py
def add_session_directory(self, path: os.PathLike | str) -> Path:
    """Adds another session folder on this machine to `session_directories`, e.g. where an app on this PC records
    to its own data folder. The folder is created if missing (an existing one, e.g. found after a crash, is fine).

    It is recorded in the run's ``run.json`` (``extra_session_directories``). Logs are still copied to
    `session_directory` only. Adding the session folder, or a folder already added, does nothing.

    Args:
        path: The folder, e.g. ``Path(rig.data_directory) / session.session_name``.

    Returns:
        The folder, as given.

    Raises:
        ValueError: If no session is registered yet.
    """
    folder = Path(path)
    known = [self.session_directory, *self._extra_session_directories]  # raises without a session
    if any(os.path.normcase(os.path.abspath(folder)) == os.path.normcase(os.path.abspath(k)) for k in known):
        return folder
    folder.mkdir(parents=True, exist_ok=True)
    self._extra_session_directories.append(folder)
    logger.info("Added session directory %s", folder)
    if self._manifest is not None:
        self.update_manifest(lambda manifest: manifest.extra_session_directories.append(str(folder)))
    return folder

register_session

register_session(
    session: Session, data_directory: PathLike
) -> Self

Registers the session model with the launcher, creates the session data directory structure, and saves repository-state metadata.

Parameters:

Name Type Description Default
session Session

The session model to register

required
data_directory PathLike

The root data directory for the session

required

Returns:

Name Type Description
Self Self

The updated instance

Raises:

Type Description
ValueError

If a session is already registered

Source code in src/clabe/launcher/_base.py
def register_session(self, session: Session, data_directory: os.PathLike) -> Self:
    """
    Registers the session model with the launcher, creates the session data
    directory structure, and saves repository-state metadata.

    Args:
        session: The session model to register
        data_directory: The root data directory for the session

    Returns:
        Self: The updated instance

    Raises:
        ValueError: If a session is already registered
    """
    if self._session is None:
        self._session = session
        self._data_directory = Path(data_directory)
        self._ensure_directory_structure()
        self._save_repository_state()
        logger.debug("Creating session directory at: %s", self.session_directory)
        bind_session(session)
    else:
        raise ValueError("Session already registered.")
    return self

run_experiment

run_experiment(
    experiment: Workflow | ExperimentCallable,
) -> None

Main entry point for the launcher execution.

Accepts a Workflow, or a (launcher) function (sync or async) run as a workflow of one step, and executes it as a run driven by this launcher's client. Unless in debug mode, validate runs as the run's first step (clabe_preflight). The run's records are written to temp_dir. Orchestrates the complete launcher workflow including validation, execution and cleanup.

Steps (including a function's single step) run on a dedicated run thread, not the main thread; code that must run on the main thread (e.g. signal.signal, some GUI toolkits) cannot be called from a step.

A launcher runs a single experiment: create a new launcher for another run.

Parameters:

Name Type Description Default
experiment Workflow | ExperimentCallable

The workflow, or the callable taking the launcher as its argument, to run

required

Raises:

Type Description
RuntimeError

If this launcher has already run an experiment.

Example
async def my_experiment(launcher: Launcher):
    # Experiment logic here (sync or async)
    pass

launcher = Launcher(...)
launcher.run_experiment(my_experiment)
Source code in src/clabe/launcher/_base.py
def run_experiment(self, experiment: "Workflow | ExperimentCallable") -> None:
    """
    Main entry point for the launcher execution.

    Accepts a [`Workflow`][clabe.workflow.Workflow], or a ``(launcher)`` function (sync or async) run as a workflow of
    one step, and executes it as a run driven by this launcher's client. Unless in debug mode,
    `validate` runs as the run's first step (``clabe_preflight``). The run's records are written to
    ``temp_dir``. Orchestrates the complete launcher workflow including validation, execution and cleanup.

    Steps (including a function's single step) run on a dedicated run thread, not the main thread; code that must
    run on the main thread (e.g. ``signal.signal``, some GUI toolkits) cannot be called from a step.

    A launcher runs a single experiment: create a new launcher for another run.

    Args:
        experiment: The workflow, or the callable taking the launcher as its argument, to run

    Raises:
        RuntimeError: If this launcher has already run an experiment.

    Example:
        ```python
        async def my_experiment(launcher: Launcher):
            # Experiment logic here (sync or async)
            pass

        launcher = Launcher(...)
        launcher.run_experiment(my_experiment)
        ```
    """
    if self._has_run:
        raise RuntimeError("A Launcher runs a single experiment; create a new Launcher for another run.")
    self._has_run = True
    workflow = as_workflow(experiment)
    _code = 0
    # Handle inside run_span so teardown logs stay under the root span (and its attributes).
    with run_span(self, experiment_name=workflow.name):
        try:
            ui.header(self.make_header())
            set_experiment = getattr(self.client, "set_experiment", None)
            if callable(set_experiment):
                set_experiment(workflow.name)
            logger.info(self._generate_diagnostic_info())

            _code = self._finish(self._run_workflow(workflow))

        except KeyboardInterrupt as e:
            # A second Ctrl+C (the first one aborts the run), or one outside the run.
            logger.error("User interrupted the process.")
            ui.notify("Interrupted by user.", MessageLevel.WARNING)
            record_exception(e)
            self._record_outcome("aborted", "Interrupted by user.", -1)
            _code = -1
        except Exception as e:  # pylint: disable=broad-except
            logger.exception("Launcher failed")
            ui.notify(f"Launcher failed: {e}", MessageLevel.ERROR)
            record_exception(e)
            self._record_outcome("failed", str(e), -1)
            _code = -1
        finally:
            try:
                self.copy_logs()
            except ValueError as ve:  # In the case session_directory fails
                ui.notify(f"Failed to copy logs from {self.temp_dir}: {ve}", MessageLevel.ERROR)
                _code = -1
                self._record_exit_code(_code)
    try:
        self._exit(_code, timeout=workflow.exit_prompt_timeout)
    finally:
        self._stop_serving()

update_manifest

update_manifest(
    change: Callable[[RunManifest], None],
) -> None

Applies change to the run manifest and rewrites run.json (nothing happens without a run).

For what only becomes known during the run, e.g. the other machines it used (see clabe.remote). Thread-safe.

Source code in src/clabe/launcher/_base.py
def update_manifest(self, change: Callable[[RunManifest], None]) -> None:
    """Applies ``change`` to the run manifest and rewrites ``run.json`` (nothing happens without a run).

    For what only becomes known during the run, e.g. the other machines it used (see [`clabe.remote`][clabe.remote]).
    Thread-safe.
    """
    with self._manifest_lock:
        if self._manifest is None:
            return
        change(self._manifest)
        self._write_manifest()

copy_logs

copy_logs(
    dst: PathLike | None = None,
    suffix: str = "Behavior/Logs",
) -> None

Closes the file handlers of the launcher and copies the temporary data to the session directory.

This method is typically called at the end of the launcher by a registered callable that transfers data.

Parameters:

Name Type Description Default
dst PathLike | None

Destination path for logs. If None, uses session_directory/suffix. Defaults to None

None
suffix str

Suffix to append to session directory path. Defaults to "Behavior/Logs"

'Behavior/Logs'
Source code in src/clabe/launcher/_base.py
def copy_logs(self, dst: os.PathLike | None = None, suffix: str = "Behavior/Logs") -> None:
    """
    Closes the file handlers of the launcher and copies the temporary data to the session directory.

    This method is typically called at the end of the launcher by a registered callable that transfers data.

    Args:
        dst: Destination path for logs. If None, uses session_directory/suffix. Defaults to None
        suffix: Suffix to append to session directory path. Defaults to "Behavior/Logs"
    """
    if self._has_copied_logs:
        return

    clabe_logging.close_file_handlers(self._logger)
    if dst is not None:
        out = self._copy_tmp_directory(dst)
    else:
        out = self._copy_tmp_directory(self.session_directory / suffix)
    ui.notify(f"Copied logs to {out}", MessageLevel.SUCCESS)
    self._has_copied_logs = True

make_header

make_header() -> str

Creates a formatted header string for the launcher.

Generates a header containing the CLABE ASCII art logo and version information for the launcher and schema models.

Returns:

Name Type Description
str str

The formatted header string

Source code in src/clabe/launcher/_base.py
def make_header(self) -> str:
    """
    Creates a formatted header string for the launcher.

    Generates a header containing the CLABE ASCII art logo and version information
    for the launcher and schema models.

    Returns:
        str: The formatted header string
    """
    _HEADER = r"""

     ██████╗██╗      █████╗ ██████╗ ███████╗
    ██╔════╝██║     ██╔══██╗██╔══██╗██╔════╝
    ██║     ██║     ███████║██████╔╝█████╗
    ██║     ██║     ██╔══██║██╔══██╗██╔══╝
    ╚██████╗███████╗██║  ██║██████╔╝███████╗
    ╚═════╝╚══════╝╚═╝  ╚═╝╚═════╝ ╚══════╝

    Command-line-interface Launcher for AIND Behavior Experiments
    Press Control+C to exit at any time.
    """

    _str = (
        f"-------------------------------\n{_HEADER}\nCLABE Version: {__version__}\n-------------------------------"
    )

    return _str

report_info

report_info() -> dict[str, object]

What this launcher knows about the session, as ReportInfo fields.

Session id, subject and experimenter once a session is registered; the repository's folder name and head commit. Never raises: what cannot be read is left out.

Source code in src/clabe/launcher/_base.py
def report_info(self) -> dict[str, object]:
    """What this launcher knows about the session, as [`ReportInfo`][clabe.reports.ReportInfo] fields.

    Session id, subject and experimenter once a session is registered; the repository's folder name and head
    commit. Never raises: what cannot be read is left out.
    """
    info: dict[str, object] = {}
    if self._session is not None:
        info["session_id"] = self._session.session_name
        info["subject"] = self._session.subject
        info["experimenter"] = list(self._session.experimenter or [])
    try:
        info["repository"] = Path(self.repository.working_dir).name
        commit = self.repository.head.commit.hexsha
        if isinstance(commit, str):
            info["commit"] = commit
    except Exception:  # a report must be made even from a broken checkout
        logger.debug("Could not read the repository for a report", exc_info=True)
    return info

validate

validate() -> None

Validates the dependencies required for the launcher to run.

Checks Git repository state, handles dirty repository conditions, and ensures all prerequisites are met for experiment execution.

Example

launcher = MyLauncher(...) try: launcher.validate() print("Validation successful") except Exception as e: print(f"Validation failed: {e}")

Source code in src/clabe/launcher/_base.py
def validate(self) -> None:
    """
    Validates the dependencies required for the launcher to run.

    Checks Git repository state, handles dirty repository conditions,
    and ensures all prerequisites are met for experiment execution.

    Example:
        launcher = MyLauncher(...)
        try:
            launcher.validate()
            print("Validation successful")
        except Exception as e:
            print(f"Validation failed: {e}")
    """
    if self.repository.is_dirty():
        logger.warning("Uncommitted files: %s", self.repository.uncommitted_changes())
        ui.notify(
            "Git repository is dirty. Discard changes before continuing unless you know what you are doing!",
            MessageLevel.WARNING,
        )
        if not self.settings.allow_dirty:
            self.repository.try_prompt_full_reset(force_reset=False)
            if self.repository.is_dirty_with_submodules():
                ui.notify(
                    "Dirty repository not allowed. Exiting. Consider running with --allow-dirty flag.",
                    MessageLevel.ERROR,
                )
                raise RuntimeError("Dirty repository not allowed.")

create_directory staticmethod

create_directory(directory: PathLike) -> None

Creates a directory at the specified path if it does not already exist.

To prevent deadlocks from network issues/auth, this function will run on a separate thread and timeout after 2 seconds.

Parameters:

Name Type Description Default
directory PathLike

The path of the directory to create

required

Raises:

Type Description
OSError

If the directory creation fails

TimeoutError

If the directory creation times out after 2 seconds

Source code in src/clabe/launcher/_base.py
@staticmethod
def create_directory(directory: os.PathLike) -> None:
    """
    Creates a directory at the specified path if it does not already exist.

    To prevent deadlocks from network issues/auth, this function will run on a separate thread
    and timeout after 2 seconds.

    Args:
        directory: The path of the directory to create

    Raises:
        OSError: If the directory creation fails
        TimeoutError: If the directory creation times out after 2 seconds
    """

    def _create_directory_with_timeout():
        if not os.path.exists(abspath(directory)):
            logger.debug("Creating  %s", directory)
            try:
                os.makedirs(directory)
            except OSError as e:
                logger.error("Failed to create directory %s: %s", directory, e)
                raise

    thread = threading.Thread(target=_create_directory_with_timeout)
    thread.start()
    thread.join(timeout=2.0)

    if thread.is_alive():
        logger.error("Directory creation timed out after 2 seconds")
        raise TimeoutError(f"Failed to create directory {directory} within 2 seconds")

save_temp_model

save_temp_model(
    model: BaseModel, directory: PathLike | None = None
) -> Path

Saves a temporary JSON representation of a schema model.

Parameters:

Name Type Description Default
model BaseModel

The schema model to save

required
directory PathLike | None

The directory to save the file in. Defaults to temp_dir if None

None

Returns:

Name Type Description
Path Path

The path to the saved file

Source code in src/clabe/launcher/_base.py
def save_temp_model(self, model: pydantic.BaseModel, directory: os.PathLike | None = None) -> Path:
    """
    Saves a temporary JSON representation of a schema model.

    Args:
        model: The schema model to save
        directory: The directory to save the file in. Defaults to temp_dir if None

    Returns:
        Path: The path to the saved file
    """
    directory = Path(directory) if directory is not None else Path(self.temp_dir)
    os.makedirs(directory, exist_ok=True)

    random_data = str(random.random()).encode("utf-8")
    sha_hash = hashlib.sha256(random_data).hexdigest()[:8]

    fname = f"{model.__class__.__name__}_{sha_hash}.json"
    fpath = os.path.join(directory, fname)
    with open(fpath, "w+", encoding="utf-8") as f:
        f.write(model.model_dump_json(indent=2))
    return Path(fpath)

LauncherCliArgs

Bases: ServiceSettings

CLI arguments for the launcher using Pydantic for validation and configuration.

Provides command-line argument parsing and validation for launcher operations.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document (--clabe-yml) ranks above every file
    return (
        init_settings,
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources,
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )