Skip to content

clabe.remote

Running on other machines: a checkout of this repository on another rig (RemoteRepository), reached through that machine's clabe daemon, which runs jobs and keeps files for the run that leased it.

WorkerClient

WorkerClient(settings: WorkerClientSettings)

Talks to the worker role of another machine's daemon.

Jobs and files need the worker's lease when someone holds it: lease takes it (and keeps renewing it in the background) so that no other run uses the machine meanwhile; release gives it back.

Source code in src/clabe/remote/_client.py
def __init__(self, settings: WorkerClientSettings) -> None:
    self.settings = settings
    self._session = requests.Session()
    if settings.token is not None and settings.token.get_secret_value():  # an empty token is no token
        self._session.headers["Authorization"] = f"Bearer {settings.token.get_secret_value()}"
    self._lease: Lease | None = None
    self._heartbeat: threading.Thread | None = None
    self._stop_heartbeat = threading.Event()

base_url property

base_url: str

The daemon's root URL.

leased property

leased: bool

Whether this client holds the worker's lease.

executor property

executor

An executor running commands on the worker (see RemoteExecutor).

info

info() -> WorkerInfo

The worker, as seen for the configured repository.

Source code in src/clabe/remote/_client.py
def info(self) -> WorkerInfo:
    """The worker, as seen for the configured repository."""
    params = {"repository": self.settings.repository} if self.settings.repository else None
    return WorkerInfo.model_validate_json(self._request("GET", "/info", params=params).content)

shares

shares() -> list[Share]

The folders the worker's machine shares on the network; empty when its daemon cannot tell (an older one).

Source code in src/clabe/remote/_client.py
def shares(self) -> list[Share]:
    """The folders the worker's machine shares on the network; empty when its daemon cannot tell (an older one)."""
    try:
        response = self._request("GET", "/shares")
    except WorkerError as exc:
        if exc.status == 404:
            return []
        raise
    return [Share.model_validate(item) for item in response.json()]

ping

ping() -> bool

Whether the worker answers.

Source code in src/clabe/remote/_client.py
def ping(self) -> bool:
    """Whether the worker answers."""
    try:
        self.info()
    except (requests.RequestException, WorkerError):
        return False
    return True

lease

lease(
    owner: str | None = None, run_id: str | None = None
) -> Lease

Takes the worker for this run and keeps renewing it until release.

Raises:

Type Description
WorkerError

423 if another run holds it, 409 if the machine runs an experiment of its own.

Source code in src/clabe/remote/_client.py
def lease(self, owner: str | None = None, run_id: str | None = None) -> Lease:
    """Takes the worker for this run and keeps renewing it until `release`.

    Raises:
        WorkerError: 423 if another run holds it, 409 if the machine runs an experiment of its own.
    """
    owner = owner or socket.gethostname()
    body = LeaseRequest(owner=owner, run_id=run_id, ttl=self.settings.lease_ttl)
    if self._lease is not None:
        body.lease_id = self._lease.lease_id
    self._lease = Lease.model_validate_json(
        self._request("POST", "/lease", json=body.model_dump(mode="json")).content
    )
    if self._heartbeat is None:
        self._stop_heartbeat.clear()
        self._heartbeat = threading.Thread(
            target=self._renew, args=(owner, run_id), name="clabe-worker-lease", daemon=True
        )
        self._heartbeat.start()
    return self._lease

release

release(*, stop_jobs: bool = False) -> None

Gives the worker back; stop_jobs also stops the jobs still running there.

Source code in src/clabe/remote/_client.py
def release(self, *, stop_jobs: bool = False) -> None:
    """Gives the worker back; ``stop_jobs`` also stops the jobs still running there."""
    self._stop_heartbeat.set()
    self._heartbeat = None
    lease, self._lease = self._lease, None
    if lease is None:
        return
    try:
        self._session.delete(
            f"{self.base_url}/api/worker/lease/{lease.lease_id}",
            params={"stop_jobs": stop_jobs},
            timeout=self.settings.timeout,
        )
    except requests.RequestException as exc:
        logger.warning("Could not release the lease on %s: %s", self.base_url, exc)

submit_command

submit_command(
    cmd_args: list[str] | str, cwd: str | None = None
) -> JobResult

Starts a command in the background; the current trace context goes along.

Source code in src/clabe/remote/_client.py
def submit_command(self, cmd_args: list[str] | str, cwd: str | None = None) -> JobResult:
    """Starts a command in the background; the current trace context goes along."""
    trace_context: dict[str, str] = {}
    propagate.inject(trace_context)
    body = JobSubmission(
        cmd=[cmd_args] if isinstance(cmd_args, str) else [str(a) for a in cmd_args],
        cwd=cwd,
        run_id=self._lease.run_id if self._lease is not None else None,
        repository=self.settings.repository,
        trace_context=trace_context,
    )
    submitted = JobResult.model_validate_json(self._request("POST", "/jobs", json=body.model_dump()).content)
    logger.info("Submitted %s to %s as job %s", body.cmd, self.base_url, submitted.job_id)
    return submitted

jobs_of

jobs_of(run_id: str) -> list[JobSummary]

The jobs of run run_id not yet collected (running, or finished with an unread result).

Source code in src/clabe/remote/_client.py
def jobs_of(self, run_id: str) -> list[JobSummary]:
    """The jobs of run ``run_id`` not yet collected (running, or finished with an unread result)."""
    return [JobSummary.model_validate(j) for j in self._request("GET", f"/runs/{run_id}/jobs").json()]

get_result

get_result(job_id: str) -> JobResult

A job's state, with its output once it ended (the worker forgets it once read).

Source code in src/clabe/remote/_client.py
def get_result(self, job_id: str) -> JobResult:
    """A job's state, with its output once it ended (the worker forgets it once read)."""
    return JobResult.model_validate_json(self._request("GET", f"/jobs/{job_id}").content)

is_running

is_running(job_id: str) -> bool

Whether a job is still running.

Source code in src/clabe/remote/_client.py
def is_running(self, job_id: str) -> bool:
    """Whether a job is still running."""
    return job_id in self.list_jobs().running

list_jobs

list_jobs() -> JobList

The worker's jobs.

Source code in src/clabe/remote/_client.py
def list_jobs(self) -> JobList:
    """The worker's jobs."""
    return JobList.model_validate_json(self._request("GET", "/jobs").content)

job_output

job_output(job_id: str, after: int = 0) -> JobOutput

A running job's output lines after line after.

Source code in src/clabe/remote/_client.py
def job_output(self, job_id: str, after: int = 0) -> JobOutput:
    """A running job's output lines after line ``after``."""
    response = self._request("GET", f"/jobs/{job_id}/output", params={"after": after})
    return JobOutput.model_validate_json(response.content)

stop_job

stop_job(job_id: str) -> JobResult

Stops a job's process.

Source code in src/clabe/remote/_client.py
def stop_job(self, job_id: str) -> JobResult:
    """Stops a job's process."""
    return JobResult.model_validate_json(self._request("POST", f"/jobs/{job_id}/stop").content)

wait_for_result

wait_for_result(
    job_id: str, timeout: float | None = None
) -> JobResult

Waits for a job to end (see monitor in the settings) and returns its result.

Raises:

Type Description
TimeoutError

The job did not end in time (or, when monitoring, stopped being seen running).

Source code in src/clabe/remote/_client.py
def wait_for_result(self, job_id: str, timeout: float | None = None) -> JobResult:
    """Waits for a job to end (see ``monitor`` in the settings) and returns its result.

    Raises:
        TimeoutError: The job did not end in time (or, when monitoring, stopped being seen running).
    """
    timeout = self.settings.timeout if timeout is None else timeout
    started = time.monotonic()
    while True:
        result = self.get_result(job_id)
        if result.status is not JobStatus.RUNNING:
            return result
        if self.settings.monitor:
            started = time.monotonic()  # seen running: the liveness window starts again
        elif time.monotonic() - started >= timeout:
            raise TimeoutError(f"Job {job_id} did not complete within {timeout} seconds")
        time.sleep(self.settings.poll_interval)

run_command

run_command(
    cmd_args: list[str] | str,
    timeout: float | None = None,
    cwd: str | None = None,
) -> JobResult

Runs a command and waits for its result.

Source code in src/clabe/remote/_client.py
def run_command(self, cmd_args: list[str] | str, timeout: float | None = None, cwd: str | None = None) -> JobResult:
    """Runs a command and waits for its result."""
    return self.wait_for_result(self.submit_command(cmd_args, cwd=cwd).job_id, timeout)

upload_file

upload_file(
    local_path: str | Path,
    remote_filename: str | None = None,
    overwrite: bool = True,
) -> FileInfo

Uploads a file to the worker's transfer directory.

Source code in src/clabe/remote/_client.py
def upload_file(
    self, local_path: str | Path, remote_filename: str | None = None, overwrite: bool = True
) -> FileInfo:
    """Uploads a file to the worker's transfer directory."""
    path = Path(local_path)
    if not path.is_file():
        raise FileNotFoundError(f"Local file not found: {path}")
    return self.upload_bytes(path.read_bytes(), remote_filename or path.name, overwrite=overwrite)

upload_bytes

upload_bytes(
    data: bytes,
    remote_filename: str,
    overwrite: bool = True,
) -> FileInfo

Uploads content as a file of the worker's transfer directory.

Source code in src/clabe/remote/_client.py
def upload_bytes(self, data: bytes, remote_filename: str, overwrite: bool = True) -> FileInfo:
    """Uploads content as a file of the worker's transfer directory."""
    if len(data) > self.settings.max_file_size:
        raise ValueError(f"{remote_filename} is larger than {self.settings.max_file_size} bytes.")
    response = self._request("PUT", f"/files/{remote_filename}", params={"overwrite": overwrite}, data=data)
    return FileInfo.model_validate_json(response.content)

upload_model

upload_model(
    model: BaseModel,
    remote_filename: str,
    overwrite: bool = True,
) -> FileInfo

Uploads a pydantic model as a JSON file.

Source code in src/clabe/remote/_client.py
def upload_model(self, model: BaseModel, remote_filename: str, overwrite: bool = True) -> FileInfo:
    """Uploads a pydantic model as a JSON file."""
    return self.upload_bytes(model.model_dump_json(indent=2).encode("utf-8"), remote_filename, overwrite)

download_file

download_file(
    remote_filename: str,
    local_path: str | Path | None = None,
) -> Path

Downloads a file of the worker's transfer directory (to local_path, default its name here).

Source code in src/clabe/remote/_client.py
def download_file(self, remote_filename: str, local_path: str | Path | None = None) -> Path:
    """Downloads a file of the worker's transfer directory (to ``local_path``, default its name here)."""
    target = Path(local_path) if local_path is not None else Path(remote_filename)
    target.write_bytes(self._request("GET", f"/files/{remote_filename}").content)
    return target

list_files

list_files() -> list[FileInfo]

The files of the worker's transfer directory.

Source code in src/clabe/remote/_client.py
def list_files(self) -> list[FileInfo]:
    """The files of the worker's transfer directory."""
    return [FileInfo.model_validate(f) for f in self._request("GET", "/files").json()]

delete_file

delete_file(remote_filename: str) -> None

Deletes a file of the worker's transfer directory.

Source code in src/clabe/remote/_client.py
def delete_file(self, remote_filename: str) -> None:
    """Deletes a file of the worker's transfer directory."""
    self._request("DELETE", f"/files/{remote_filename}")

delete_all_files

delete_all_files() -> list[str]

Deletes every file of the worker's transfer directory; returns their names.

Source code in src/clabe/remote/_client.py
def delete_all_files(self) -> list[str]:
    """Deletes every file of the worker's transfer directory; returns their names."""
    return self._request("DELETE", "/files").json()

run

run(command: Command) -> CommandResult

Runs command on the worker, e.g. app.run(executor=client).

Source code in src/clabe/remote/_client.py
def run(self, command: Command) -> CommandResult:
    """Runs ``command`` on the worker, e.g. ``app.run(executor=client)``."""
    return self.executor.run(command)

run_async async

run_async(command: Command) -> CommandResult

Runs command on the worker, e.g. await app.run_async(executor=client).

Source code in src/clabe/remote/_client.py
async def run_async(self, command: Command) -> CommandResult:
    """Runs ``command`` on the worker, e.g. ``await app.run_async(executor=client)``."""
    return await self.executor.run_async(command)

WorkerClientSettings

Bases: ServiceSettings

Settings of a WorkerClient (worker_client: in clabe.yml).

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,
    )

WorkerError

WorkerError(message: str, status: int)

Bases: RuntimeError

The worker refused or failed a request; status is the HTTP status.

Source code in src/clabe/remote/_client.py
def __init__(self, message: str, status: int) -> None:
    super().__init__(message)
    self.status = status

RemoteExecutor

RemoteExecutor(
    client: WorkerClient,
    timeout: float | None = None,
    poll_interval: float | None = None,
    cwd: str | None = None,
    path_mapping: Mapping[str, str] | None = None,
)

Runs commands on a worker; any app runs on it unchanged (app.run(executor=...)).

Inputs a command declares (Command.inputs) are sent along with it, and path_mapping rewrites local path prefixes to their location on the worker. A cancelled run_async (e.g. the run was aborted) stops the job on the worker. To run apps in a checkout of this repository on another machine, use RemoteRepository, which builds on this executor.

Parameters:

Name Type Description Default
client WorkerClient

The worker's client.

required
timeout float | None

Seconds to wait for a job (see the client's monitor); the client's by default.

None
poll_interval float | None

Seconds between checks of a job; the client's by default.

None
cwd str | None

Working directory on the worker; the repository's by default.

None
path_mapping Mapping[str, str] | None

Local path prefixes to rewrite in commands, mapped to their location on the worker.

None
Source code in src/clabe/remote/_executor.py
def __init__(
    self,
    client: "WorkerClient",
    timeout: float | None = None,
    poll_interval: float | None = None,
    cwd: str | None = None,
    path_mapping: Mapping[str, str] | None = None,
) -> None:
    self.client = client
    self.timeout = timeout
    self.poll_interval = poll_interval
    self.cwd = cwd
    self.path_mapping = dict(path_mapping or {})
    self._python_executable: str | None = None

host property

host: str | None

The worker's host name (apps use it to reach services the command starts there).

run

run(command: Command[Any]) -> CommandResult

Runs the command on the worker and waits for it; inside a run its output shows as a live activity.

Source code in src/clabe/remote/_executor.py
def run(self, command: Command[Any]) -> CommandResult:
    """Runs the command on the worker and waits for it; inside a run its output shows as a live activity."""
    logger.info("Running on %s: %s", self.client.base_url, command.cmd)
    cmd = self._prepare(command)
    job_id = self.client.submit_command(cmd, cwd=self.cwd).job_id
    record_job(self.client, job_id, cmd)
    return self.wait(job_id, _describe(cmd))

wait

wait(
    job_id: str, description: str = "job"
) -> CommandResult

Waits for a job already on the worker (e.g. one a crashed launcher started) and returns its result.

Source code in src/clabe/remote/_executor.py
def wait(self, job_id: str, description: str = "job") -> CommandResult:
    """Waits for a job already on the worker (e.g. one a crashed launcher started) and returns its result."""
    with self._activity(f"{description} on {self.host}") as follow:
        started = time.monotonic()
        while True:
            time.sleep(self._interval)
            follow.poll(job_id)
            result = self.client.get_result(job_id)
            if result.status is not JobStatus.RUNNING:
                follow.poll(job_id, final=True)
                return self._result(result)
            started = self._check_timeout(job_id, started)

run_async async

run_async(command: Command[Any]) -> CommandResult

Runs the command on the worker without blocking the event loop; cancelling it stops the job. Inside a run its output shows as a live activity.

Source code in src/clabe/remote/_executor.py
async def run_async(self, command: Command[Any]) -> CommandResult:
    """Runs the command on the worker without blocking the event loop; cancelling it stops the job. Inside a
    run its output shows as a live activity."""
    cmd = await asyncio.to_thread(self._prepare, command)
    job_id = (await asyncio.to_thread(self.client.submit_command, cmd, self.cwd)).job_id
    await asyncio.to_thread(record_job, self.client, job_id, cmd)
    return await self.wait_async(job_id, _describe(cmd))

wait_async async

wait_async(
    job_id: str, description: str = "job"
) -> CommandResult

Asynchronous wait; cancelling it stops the job.

Source code in src/clabe/remote/_executor.py
async def wait_async(self, job_id: str, description: str = "job") -> CommandResult:
    """Asynchronous `wait`; cancelling it stops the job."""
    try:
        with self._activity(f"{description} on {self.host}") as follow:
            started = time.monotonic()
            while True:
                await asyncio.sleep(self._interval)
                await asyncio.to_thread(follow.poll, job_id)
                result = await asyncio.to_thread(self.client.get_result, job_id)
                if result.status is not JobStatus.RUNNING:
                    await asyncio.to_thread(follow.poll, job_id, final=True)
                    return self._result(result)
                started = self._check_timeout(job_id, started)
    except asyncio.CancelledError:
        logger.info("Stopping job %s on %s", job_id, self.client.base_url)
        await asyncio.to_thread(self.client.stop_job, job_id)
        raise

FileInfo

Bases: BaseModel

A file in the worker's transfer directory.

JobResult

Bases: BaseModel

A job's state, and its output once it ended.

JobStatus

Bases: str, Enum

Where a job is.

JobSummary

Bases: BaseModel

A job, as listed for the run it belongs to.

Lease

Bases: BaseModel

The worker taken by a run; requests carrying it (X-Clabe-Lease) are served, others refused.

Share

Bases: BaseModel

A folder the worker's machine shares on the network.

WorkerInfo

Bases: BaseModel

A worker, as seen for one of its repositories.

RemoteRepository

RemoteRepository(
    client: WorkerClient,
    path: str | None = None,
    *,
    local_path: PathLike | str = ".",
    data_roots: Mapping[str, str] | None = None,
    detach_on_abort: bool = False,
)

A checkout of this repository on another machine, reached through that machine's clabe daemon (its worker).

The repository must be one the remote daemon offers (found under its roots, or in DAEMON_CLABE_REPOSITORIES); commands run in it and in its environment by default. The first command (or lease) takes the worker's lease, so no other run uses the machine meanwhile; it is renewed in the background and given back by release (or at exit).

Example
remote = RemoteRepository.from_computer_name("rig-b", data_roots={r"D:\data": r"\\rig-b\data"})
remote.ensure_running()
remote.verify()
remote.register_session(session, fip_rig.data_directory)
fip_app = AindBehaviorServicesBonsaiApp("./Aind.Physiology.Fip/src/main.bonsai", rig=fip_rig, session=session)
await fip_app.run_async(executor=remote)
source = remote.session_directory_unc  # e.g. \\rig-b\data\<session name>

Initializes the remote repository.

Parameters:

Name Type Description Default
client WorkerClient

Client of the remote machine's worker (its repository setting names the checkout).

required
path str | None

Path of the repository on the remote machine. Defaults to the worker's repository. When given, verify checks that it is the worker's repository.

None
local_path PathLike | str

Path of the local repository the remote one is compared against.

'.'
data_roots Mapping[str, str] | None

Maps data directories on the remote machine to the network shares exposing them, e.g. {r"D:\data": r"\\rig-b\data"}. Optional: by default to_unc uses the folders the machine shares (its daemon lists them), then the drive's administrative share. Entries here take precedence, e.g. for a share reached through another server name.

None
detach_on_abort bool

Keep the commands running on the remote machine when the run does not complete (e.g. a recording that must outlive the launcher). By default they are stopped with the run.

False
Source code in src/clabe/remote/_repository.py
def __init__(
    self,
    client: WorkerClient,
    path: str | None = None,
    *,
    local_path: os.PathLike | str = ".",
    data_roots: Mapping[str, str] | None = None,
    detach_on_abort: bool = False,
) -> None:
    """
    Initializes the remote repository.

    Args:
        client: Client of the remote machine's worker (its ``repository`` setting names the checkout).
        path: Path of the repository on the remote machine. Defaults to the worker's repository.
            When given, `verify` checks that it is the worker's repository.
        local_path: Path of the local repository the remote one is compared against.
        data_roots: Maps data directories on the remote machine to the network shares exposing them,
            e.g. ``{r"D:\\data": r"\\\\rig-b\\data"}``. Optional: by default `to_unc` uses the folders the
            machine shares (its daemon lists them), then the drive's administrative share. Entries here take
            precedence, e.g. for a share reached through another server name.
        detach_on_abort: Keep the commands running on the remote machine when the run does not complete (e.g.
            a recording that must outlive the launcher). By default they are stopped with the run.
    """
    self.client = client
    self.detach_on_abort = detach_on_abort
    self._path = path
    self.local_path = local_path
    self.data_roots = {PureWindowsPath(local): PureWindowsPath(unc) for local, unc in (data_roots or {}).items()}
    self._info: WorkerInfo | None = None
    self._shares: dict[PureWindowsPath, PureWindowsPath] | None = None
    self._session: Session | None = None
    self._data_directory: PurePath | None = None

host property

host: str

Hostname of the remote machine, as given in the worker's URL.

path property

path: str

Path of the repository on the remote machine.

data_directory property

data_directory: PurePath

Root data directory on the remote machine, set by register_session.

session_directory property

session_directory: PurePath

Session directory as the remote machine sees it, e.g. to configure where an app saves its data.

session_directory_unc property

session_directory_unc: PureWindowsPath

Session directory as other machines reach it through its network share, e.g. for watchdog or mappers.

from_computer_name classmethod

from_computer_name(
    computer_name: str,
    port: int = DEFAULT_PORT,
    path: str | None = None,
    *,
    repository: str | None = None,
    local_path: PathLike | str = ".",
    data_roots: Mapping[str, str] | None = None,
) -> Self

Connects to the daemon of a machine by its computer name, e.g. a rig's computer_name: nothing to configure. The other client settings (a token, timeouts), when needed, come from the experiment's worker_client section.

Parameters:

Name Type Description Default
computer_name str

Network name of the remote machine.

required
port int

Port of its daemon.

DEFAULT_PORT
path str | None

Path of the repository on the remote machine. See __init__.

None
repository str | None

The remote daemon's name for the repository; by default this repository's folder name.

None
local_path PathLike | str

Path of the local repository the remote one is compared against.

'.'
data_roots Mapping[str, str] | None

Maps data directories on the remote machine to the network shares exposing them. Defaults to the drives' administrative shares.

None
Source code in src/clabe/remote/_repository.py
@classmethod
def from_computer_name(
    cls,
    computer_name: str,
    port: int = DEFAULT_PORT,
    path: str | None = None,
    *,
    repository: str | None = None,
    local_path: os.PathLike | str = ".",
    data_roots: Mapping[str, str] | None = None,
) -> Self:
    """Connects to the daemon of a machine by its computer name, e.g. a rig's ``computer_name``: nothing to
    configure. The other client settings (a token, timeouts), when needed, come from the experiment's
    ``worker_client`` section.

    Args:
        computer_name: Network name of the remote machine.
        port: Port of its daemon.
        path: Path of the repository on the remote machine. See `__init__`.
        repository: The remote daemon's name for the repository; by default this repository's folder name.
        local_path: Path of the local repository the remote one is compared against.
        data_roots: Maps data directories on the remote machine to the network shares exposing them.
            Defaults to the drives' administrative shares.
    """
    settings = WorkerClientSettings(
        url=f"http://{computer_name}:{port}", repository=repository or Path(local_path).resolve().name
    )
    return cls(WorkerClient(settings), path, local_path=local_path, data_roots=data_roots)

info

info(refresh: bool = False) -> WorkerInfo

Returns the remote worker's information, fetching it on first use or when refresh is True.

Source code in src/clabe/remote/_repository.py
def info(self, refresh: bool = False) -> WorkerInfo:
    """Returns the remote worker's information, fetching it on first use or when ``refresh`` is True."""
    if self._info is None or refresh:
        self._info = self.client.info()
    return self._info

lease

lease(run_id: str | None = None) -> None

Takes the remote machine for this run (the first command does it anyway); renewed until released.

Parameters:

Name Type Description Default
run_id str | None

The run to take it for; by default the running one. A restarted launcher passes the run id of the session it recovers (see reattach).

None

Raises:

Type Description
WorkerError

423 if another run holds the machine, 409 if it runs an experiment of its own.

Source code in src/clabe/remote/_repository.py
def lease(self, run_id: str | None = None) -> None:
    """Takes the remote machine for this run (the first command does it anyway); renewed until released.

    Args:
        run_id: The run to take it for; by default the running one. A restarted launcher passes the run id of
            the session it recovers (see `reattach`).

    Raises:
        WorkerError: 423 if another run holds the machine, 409 if it runs an experiment of its own.
    """
    if self.client.leased:
        return
    from ..workflow._records import ACTIVE_STEP

    context = ACTIVE_STEP.get()
    run_id = run_id or (context.run.id if context is not None else None)
    self.client.lease(owner=f"{socket.gethostname()} ({Path(self.local_path).resolve().name})", run_id=run_id)
    atexit.register(self.client.release)
    if context is not None:
        context.run.add_finalizer(self._run_ended)
        record_worker(self.client)
    logger.info("Took %s for this run", self.host)

reattach

reattach(run_id: str) -> list[JobSummary]

Takes the remote machine back for run run_id and returns that run's jobs still there.

For recovering a session after the launcher crashed: its jobs kept running on the remote machine, and for a grace period after its lease expired only the same run may take the machine back. The run id and the machine are in the crashed session's run.json (run_id, workers). Collect each job's result with wait_for.

Source code in src/clabe/remote/_repository.py
def reattach(self, run_id: str) -> list[JobSummary]:
    """Takes the remote machine back for run ``run_id`` and returns that run's jobs still there.

    For recovering a session after the launcher crashed: its jobs kept running on the remote machine, and for a
    grace period after its lease expired only the same run may take the machine back. The run id and the
    machine are in the crashed session's ``run.json`` (``run_id``, ``workers``). Collect each job's result with
    `wait_for`.
    """
    self.lease(run_id)
    jobs = self.client.jobs_of(run_id)
    logger.info("Reattached to %s: %d job(s) of run %s", self.host, len(jobs), run_id)
    return jobs

wait_for

wait_for(job_id: str) -> CommandResult

Waits for a job already on the remote machine (see reattach) and returns its result.

Source code in src/clabe/remote/_repository.py
def wait_for(self, job_id: str) -> CommandResult:
    """Waits for a job already on the remote machine (see `reattach`) and returns its result."""
    return self._executor().wait(job_id)

wait_for_async async

wait_for_async(job_id: str) -> CommandResult

Asynchronous wait_for; cancelling it stops the job.

Source code in src/clabe/remote/_repository.py
async def wait_for_async(self, job_id: str) -> CommandResult:
    """Asynchronous `wait_for`; cancelling it stops the job."""
    return await self._executor().wait_async(job_id)

release

release(*, stop_jobs: bool = False) -> None

Gives the remote machine back; stop_jobs also stops what still runs there.

Source code in src/clabe/remote/_repository.py
def release(self, *, stop_jobs: bool = False) -> None:
    """Gives the remote machine back; ``stop_jobs`` also stops what still runs there."""
    self.client.release(stop_jobs=stop_jobs)

ensure_running

ensure_running(
    timeout: float = 60.0, poll_interval: float = 1.0
) -> None

Starts the remote daemon through its scheduled task (clabe daemon install) if it does not respond.

Parameters:

Name Type Description Default
timeout float

Seconds to wait for the daemon to respond after starting the task.

60.0
poll_interval float

Seconds between connection attempts.

1.0

Raises:

Type Description
ConnectionError

If the remote machine's name cannot be resolved to an address.

TimeoutError

If the daemon does not respond within timeout.

Source code in src/clabe/remote/_repository.py
def ensure_running(self, timeout: float = 60.0, poll_interval: float = 1.0) -> None:
    """Starts the remote daemon through its scheduled task (``clabe daemon install``) if it does not respond.

    Args:
        timeout: Seconds to wait for the daemon to respond after starting the task.
        poll_interval: Seconds between connection attempts.

    Raises:
        ConnectionError: If the remote machine's name cannot be resolved to an address.
        TimeoutError: If the daemon does not respond within ``timeout``.
    """
    if self.client.ping():
        return
    _check_resolvable(self.host)
    logger.info("The daemon on %s is not responding; starting its scheduled task '%s'", self.host, TASK_NAME)
    start_task(host=self.host)
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        time.sleep(poll_interval)
        if self.client.ping():
            logger.info("The daemon on %s is running", self.host)
            return
    raise TimeoutError(f"The daemon on {self.host} did not respond within {timeout} seconds of starting it")

verify

verify(allow_dirty: bool = False) -> None

Checks that the remote repository runs the same code as the local one.

Compares the worker's repository path, and the repository URL and commit of the repository and each submodule. Because the lockfile is tracked, a matching clean commit also implies the same locked dependencies. A different clabe version of the daemon is only warned about.

Parameters:

Name Type Description Default
allow_dirty bool

Whether to accept uncommitted changes in the remote repository.

False

Raises:

Type Description
RepositoryMismatchError

Listing every difference found.

Source code in src/clabe/remote/_repository.py
def verify(self, allow_dirty: bool = False) -> None:
    """Checks that the remote repository runs the same code as the local one.

    Compares the worker's repository path, and the repository URL and commit of the repository and each
    submodule. Because the lockfile is tracked, a matching clean commit also implies the same locked
    dependencies. A different clabe version of the daemon is only warned about.

    Args:
        allow_dirty: Whether to accept uncommitted changes in the remote repository.

    Raises:
        RepositoryMismatchError: Listing every difference found.
    """
    info = self.info(refresh=True)
    if info.clabe_version != __version__:
        logger.warning(
            "The daemon on %s runs clabe %s, not %s; continuing on a best-effort basis",
            self.host,
            info.clabe_version,
            __version__,
        )
    problems: list[str] = []
    if self._path is not None and self._remote_path(self._path) != self._remote_path(info.working_dir):
        problems.append(f"the worker's repository is {info.working_dir}, not {self._path}")
    if problems:
        raise RepositoryMismatchError(f"Remote repository on {self.host} does not match: " + "; ".join(problems))

    result = self._executor().run(
        Command(
            cmd=[info.python_executable, "-m", "clabe.cli", "repository-state", "."], output_parser=identity_parser
        )
    )
    remote_state = GitRepositoryMetadata.model_validate_json(result.stdout or "")
    record_worker(self.client, lambda record: setattr(record, "repository_state", remote_state))
    remote = _flatten_commits(remote_state)
    local = _flatten_commits(GitRepository(self.local_path).get_metadata())

    if _normalize_url(remote["."].url) != _normalize_url(local["."].url):
        problems.append(f"remote URL {remote['.'].url} != local {local['.'].url}")
    for key in sorted(local.keys() | remote.keys()):
        if key not in remote or key not in local:
            problems.append(f"{key}: only present {'locally' if key in local else 'remotely'}")
            continue
        if remote[key].commit_sha != local[key].commit_sha:
            problems.append(f"{key}: commit {remote[key].commit_sha} != local {local[key].commit_sha}")
        if remote[key].is_dirty and not allow_dirty:
            problems.append(f"{key}: has uncommitted changes")
    if problems:
        raise RepositoryMismatchError(f"Remote repository on {self.host} does not match: " + "; ".join(problems))
    logger.info("Remote repository on %s matches the local one (%s)", self.host, local["."].commit_sha)

to_unc

to_unc(path: PathLike | str) -> PureWindowsPath

Translates a path on the remote machine to the network share path other machines reach it by.

Paths under none of the data_roots are reached through the drive's administrative share; see to_unc.

Raises:

Type Description
ValueError

If the path is under none of the data_roots and has no drive letter.

Source code in src/clabe/remote/_repository.py
def to_unc(self, path: os.PathLike | str) -> PureWindowsPath:
    """Translates a path on the remote machine to the network share path other machines reach it by.

    Paths under none of the ``data_roots`` are reached through the drive's administrative share; see
    `to_unc`.

    Raises:
        ValueError: If the path is under none of the ``data_roots`` and has no drive letter.
    """
    try:
        return to_unc(path, {str(local): str(unc) for local, unc in self._roots().items()}, host=self.host)
    except ValueError as e:
        raise ValueError(f"{e} (on {self.host})") from e

register_session

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

Registers the session this machine records data for, and creates its session directory there.

The remote counterpart of register_session. Optional: only data_directory, session_directory and session_directory_unc need it.

Raises:

Type Description
ValueError

If a session is already registered, or the session has no name.

Source code in src/clabe/remote/_repository.py
def register_session(self, session: Session, data_directory: os.PathLike | str) -> Self:
    """Registers the session this machine records data for, and creates its session directory there.

    The remote counterpart of [`register_session`][clabe.launcher.Launcher.register_session]. Optional: only
    `data_directory`, `session_directory` and `session_directory_unc` need it.

    Raises:
        ValueError: If a session is already registered, or the session has no name.
    """
    if self._session is not None:
        raise ValueError("Session already registered.")
    if session.session_name is None:
        raise ValueError("session.session_name is not set.")
    self._session = session
    self._data_directory = self._remote_path(data_directory)
    self.mkdir(self.session_directory)
    logger.debug("Created session directory on %s at %s", self.host, self.session_directory)
    try:
        unc: str | None = str(self.session_directory_unc)
    except ValueError:
        unc = None
    local = str(self.session_directory)

    def note(record) -> None:
        """Where this machine keeps the session's data, in the run's record of it (``run.json``)."""
        record.session_directory, record.session_directory_unc = local, unc

    record_worker(self.client, note)
    return self

mkdir

mkdir(path: PathLike | str) -> None

Creates a directory, and its missing parents, on the remote machine.

Source code in src/clabe/remote/_repository.py
def mkdir(self, path: os.PathLike | str) -> None:
    """Creates a directory, and its missing parents, on the remote machine."""
    self._run_python("import pathlib, sys; pathlib.Path(sys.argv[1]).mkdir(parents=True, exist_ok=True)", path)

write_file

write_file(
    path: PathLike | str, content: str | bytes
) -> None

Writes a file on the remote machine, creating its directory if needed.

The content is uploaded to the worker's transfer directory and then moved into place. It is limited to the client's max_file_size.

Parameters:

Name Type Description Default
path PathLike | str

The file, as the remote machine sees it. Replaced if it exists.

required
content str | bytes

The content. Text is written as UTF-8.

required
Source code in src/clabe/remote/_repository.py
def write_file(self, path: os.PathLike | str, content: str | bytes) -> None:
    """Writes a file on the remote machine, creating its directory if needed.

    The content is uploaded to the worker's transfer directory and then moved into place. It is limited to the
    client's ``max_file_size``.

    Args:
        path: The file, as the remote machine sees it. Replaced if it exists.
        content: The content. Text is written as UTF-8.
    """
    name = self._remote_path(path).name
    self.lease()
    with tempfile.TemporaryDirectory() as staging:
        upload_path = Path(staging) / f"clabe_{uuid.uuid4().hex}_{name}"
        upload_path.write_bytes(content.encode("utf-8") if isinstance(content, str) else content)
        upload = self.client.upload_file(upload_path)
    move = (
        "import pathlib, shutil, sys; target = pathlib.Path(sys.argv[2]); "
        "target.parent.mkdir(parents=True, exist_ok=True); shutil.move(sys.argv[1], target)"
    )
    self._run_python(move, upload.path, path)
    logger.debug("Wrote %s on %s", path, self.host)

run

run(command: Command[Any]) -> CommandResult

Runs a command in the remote repository and waits for it (an Executor).

Paths under the local repository are rewritten to the remote one, and the command's inputs are copied to the remote machine.

Raises:

Type Description
CommandError

If the command exits with a non-zero code.

Source code in src/clabe/remote/_repository.py
def run(self, command: Command[Any]) -> CommandResult:
    """Runs a command in the remote repository and waits for it (an [`Executor`][clabe.apps.Executor]).

    Paths under the local repository are rewritten to the remote one, and the command's ``inputs`` are copied
    to the remote machine.

    Raises:
        CommandError: If the command exits with a non-zero code.
    """
    return self._executor().run(command)

run_async async

run_async(command: Command[Any]) -> CommandResult

Asynchronous version of run, e.g. await app.run_async(executor=remote); cancelling it stops the command on the remote machine.

Source code in src/clabe/remote/_repository.py
async def run_async(self, command: Command[Any]) -> CommandResult:
    """Asynchronous version of `run`, e.g. ``await app.run_async(executor=remote)``; cancelling it stops
    the command on the remote machine."""
    return await self._executor().run_async(command)

RepositoryMismatchError

Bases: RuntimeError

Raised when a remote repository does not match the local one.

to_unc

to_unc(
    path: PathLike | str,
    data_roots: Mapping[str, str] | None = None,
    host: str | None = None,
) -> PureWindowsPath

Translates a path on another machine to the network share path it is reached by.

Needs no connection to that machine, e.g. to find the data of a session recorded there earlier. A path under none of the data_roots is reached through its drive's administrative share on host, e.g. D:\data on rig-b as \\rig-b\D$\data, which needs administrator rights on that machine.

Parameters:

Name Type Description Default
path PathLike | str

An absolute path on the other machine.

required
data_roots Mapping[str, str] | None

Maps data directories on that machine to the network shares exposing them, e.g. {r"D:\data": r"\\rig-b\data"}. Takes precedence over the administrative share.

None
host str | None

Name of the other machine, for its administrative shares.

None

Returns:

Type Description
PureWindowsPath

The same location under its network share.

Raises:

Type Description
ValueError

If the path is under none of the data_roots and there is no host or drive to fall back on.

Source code in src/clabe/remote/_repository.py
def to_unc(
    path: os.PathLike | str, data_roots: Mapping[str, str] | None = None, host: str | None = None
) -> PureWindowsPath:
    """Translates a path on another machine to the network share path it is reached by.

    Needs no connection to that machine, e.g. to find the data of a session recorded there earlier. A path under
    none of the ``data_roots`` is reached through its drive's administrative share on ``host``, e.g. ``D:\\data``
    on ``rig-b`` as ``\\\\rig-b\\D$\\data``, which needs administrator rights on that machine.

    Args:
        path: An absolute path on the other machine.
        data_roots: Maps data directories on that machine to the network shares exposing them,
            e.g. ``{r"D:\\data": r"\\\\rig-b\\data"}``. Takes precedence over the administrative share.
        host: Name of the other machine, for its administrative shares.

    Returns:
        The same location under its network share.

    Raises:
        ValueError: If the path is under none of the ``data_roots`` and there is no ``host`` or drive to fall back on.
    """
    path = PureWindowsPath(path)
    roots = {PureWindowsPath(local): PureWindowsPath(unc) for local, unc in (data_roots or {}).items()}
    # Most specific root first, so nested roots map to their own share
    for root in sorted(roots, key=lambda r: len(r.parts), reverse=True):
        if path.is_relative_to(root):
            return roots[root] / path.relative_to(root)
    # A drive letter path, e.g. D:\data, but not a path that already is a share
    if host is not None and len(path.drive) == 2 and path.drive.endswith(":"):
        return PureWindowsPath(f"//{host}/{path.drive[0]}$/") / path.relative_to(path.anchor)
    raise ValueError(f"{path} is not under any data root: {[str(r) for r in roots]}")