Skip to content

clabe.hub

The clabe hub: an optional service (e.g. in Docker) that follows a fleet of rigs through their daemons, shows which ones wait for an answer, and re-exposes each rig under /rigs/<id>/ so the web UI works fleet-wide.

Rigs never depend on it: the hub dials in as an ordinary client of their daemons.

Fleet

Fleet(
    settings: HubSettings,
    client: AsyncClient | None = None,
    reports: ReportStore | None = None,
)

Polls every rig's daemon (and, when it runs an experiment, the run) and keeps what it saw.

With a report store, it also collects each rig's issue reports (every report_interval seconds, when the rig has some): downloads each, stores it, and only then deletes it on the rig.

Source code in src/clabe/hub/_fleet.py
def __init__(
    self,
    settings: HubSettings,
    client: httpx.AsyncClient | None = None,
    reports: "ReportStore | None" = None,
) -> None:
    self.settings = settings
    self.rigs = {rig.id: rig for rig in settings.rigs}
    self.status = {rig.id: RigStatus(id=rig.id, url=rig.url) for rig in settings.rigs}
    self.reports = reports
    self._client = client or httpx.AsyncClient(timeout=5.0)
    self._task: asyncio.Task | None = None
    self._collected_at: dict[str, float] = {}
    self._purged_at: float | None = None
    self._refused: set[str] = set()

rig

rig(rig_id: str) -> RigConfig | None

The rig called rig_id.

Source code in src/clabe/hub/_fleet.py
def rig(self, rig_id: str) -> RigConfig | None:
    """The rig called ``rig_id``."""
    return self.rigs.get(rig_id)

statuses

statuses(
    statuses: list[RigStatus] | None = None,
) -> list[RigStatus]

Every rig as last polled (or those given), with how many of its reports the hub stores.

Source code in src/clabe/hub/_fleet.py
def statuses(self, statuses: list[RigStatus] | None = None) -> list[RigStatus]:
    """Every rig as last polled (or those given), with how many of its reports the hub stores."""
    statuses = list(self.status.values()) if statuses is None else statuses
    counts = self.reports.counts_by_rig() if self.reports is not None else {}
    return [s.model_copy(update={"reports_stored": counts.get(s.id, 0)}) for s in statuses]

inbox

inbox() -> list[RigStatus]

The rigs waiting for an answer, longest-waiting first.

Source code in src/clabe/hub/_fleet.py
def inbox(self) -> list[RigStatus]:
    """The rigs waiting for an answer, longest-waiting first."""
    waiting = [s for s in self.status.values() if s.waiting is not None]
    return sorted(waiting, key=lambda s: s.waiting.since)  # type: ignore[union-attr]

poll_once async

poll_once(*, collect: bool = False) -> None

Refreshes every rig's status, and collects reports where due (or everywhere, with collect).

Source code in src/clabe/hub/_fleet.py
async def poll_once(self, *, collect: bool = False) -> None:
    """Refreshes every rig's status, and collects reports where due (or everywhere, with ``collect``)."""
    await self._purge()
    await asyncio.gather(*(self._poll(rig, collect) for rig in self.rigs.values()))

run async

run() -> None

Polls forever.

Source code in src/clabe/hub/_fleet.py
async def run(self) -> None:
    """Polls forever."""
    while True:
        await self.poll_once()
        await asyncio.sleep(self.settings.poll_interval)

start

start() -> None

Starts polling in the background (on the running loop).

Source code in src/clabe/hub/_fleet.py
def start(self) -> None:
    """Starts polling in the background (on the running loop)."""
    if self._task is None:
        self._task = asyncio.ensure_future(self.run())

stop async

stop() -> None

Stops polling.

Source code in src/clabe/hub/_fleet.py
async def stop(self) -> None:
    """Stops polling."""
    if self._task is not None:
        self._task.cancel()
        self._task = None

collect async

collect(rig: RigConfig) -> int

Collects a rig's issue reports: downloads each one not stored yet, stores it, then deletes it on the rig (one already stored is just deleted there). Failures are logged and retried next time.

Returns:

Type Description
int

How many reports were stored.

Source code in src/clabe/hub/_fleet.py
async def collect(self, rig: RigConfig) -> int:
    """Collects a rig's issue reports: downloads each one not stored yet, stores it, then deletes it on the rig
    (one already stored is just deleted there). Failures are logged and retried next time.

    Returns:
        How many reports were stored.
    """
    if self.reports is None:
        return 0
    try:
        listed = (await self._get(rig, "/api/daemon/reports")).json()
    except (httpx.HTTPError, ValueError) as exc:
        logger.warning("Could not list the reports of %s: %s", rig.id, exc)
        return 0
    stored = 0
    for item in listed:
        report_id = str(item.get("report_id", "")) if isinstance(item, dict) else ""
        if not re.fullmatch(REPORT_ID_PATTERN, report_id) or report_id in self._refused:
            continue
        try:
            stored += await self._collect_one(rig, report_id)
        except (httpx.HTTPError, OSError, sqlite3.Error, ValueError) as exc:  # retried next time
            logger.warning("Could not collect report %s of %s: %s", report_id, rig.id, exc)
    return stored

HubSettings

Bases: EnvSettings

Settings of clabe hub run, from environment variables without a prefix (the hub runs in its own container) or a .env file in the working directory (see docker/hub/.env.example). Rigs are id=url items separated by ; (or a JSON list, for per-rig tokens):

TOKEN=...                             # the hub's own
RIG_TOKEN=...                         # the rigs' daemon token (their DAEMON_CLABE_TOKEN)
RIGS=rig-3=http://rig-3:24070;rig-4=http://rig-4:24070

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, ...]

Keyword arguments, then the environment, then a .env file when the class names one.

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, ...]:
    """Keyword arguments, then the environment, then a ``.env`` file when the class names one."""
    return (init_settings, env_settings, dotenv_settings)

RigConfig

Bases: BaseModel

A rig the hub follows.

RigStatus

Bases: BaseModel

What the hub last saw of a rig.

Waiting

Bases: BaseModel

A prompt a rig's run is waiting on.

InspectCache

InspectCache(
    directory: Path | None = None, ttl: float = INSPECT_TTL
)

Exports opened for a look, kept in a temporary folder for INSPECT_TTL seconds after their last use.

Source code in src/clabe/hub/_reports.py
def __init__(self, directory: Path | None = None, ttl: float = INSPECT_TTL) -> None:
    self._directory = Path(directory) if directory else None
    self.ttl = ttl
    self._lock = threading.Lock()

directory property

directory: Path

Where the exports are kept (a temporary folder, made at first use, unless one was given).

add

add(data: bytes) -> InspectResult

Keeps an export for a look.

Raises:

Type Description
ValueError

Not a zip.

Source code in src/clabe/hub/_reports.py
def add(self, data: bytes) -> InspectResult:
    """Keeps an export for a look.

    Raises:
        ValueError: Not a zip.
    """
    self.expire()
    inspect_id = uuid.uuid4().hex
    path = self.directory / f"{inspect_id}.zip"
    path.write_bytes(data)
    try:
        files = zip_entries(path)
    except ValueError:
        path.unlink(missing_ok=True)
        raise
    try:
        report = read_report_info(path) if any(f.path == REPORT_FILE for f in files) else None
    except ValueError:
        report = None
    return InspectResult(inspect_id=inspect_id, files=files, report=report)

path

path(inspect_id: str) -> Path | None

The zip of an opened export, if still kept (its use keeps it longer).

Source code in src/clabe/hub/_reports.py
def path(self, inspect_id: str) -> Path | None:
    """The zip of an opened export, if still kept (its use keeps it longer)."""
    self.expire()
    if not re.fullmatch(REPORT_ID_PATTERN, inspect_id):
        return None
    path = self.directory / f"{inspect_id}.zip"
    if not path.is_file():
        return None
    path.touch()
    return path

expire

expire() -> None

Forgets the exports unused for longer than the time they are kept.

Source code in src/clabe/hub/_reports.py
def expire(self) -> None:
    """Forgets the exports unused for longer than the time they are kept."""
    cutoff = time.time() - self.ttl
    directory = self.directory
    with self._lock:
        for path in directory.glob("*.zip"):
            try:
                if path.stat().st_mtime < cutoff:
                    path.unlink()
            except OSError:
                continue

close

close() -> None

Forgets every export.

Source code in src/clabe/hub/_reports.py
def close(self) -> None:
    """Forgets every export."""
    if self._directory is not None:
        shutil.rmtree(self._directory, ignore_errors=True)
        self._directory = None

ReportPage

Bases: BaseModel

A page of reports, and how many match in all.

ReportStore

ReportStore(data_dir: Path)

The hub's collected reports: rows in SQLite, zips on disk. Safe to use from several threads.

Source code in src/clabe/hub/_reports.py
def __init__(self, data_dir: Path) -> None:
    self.data_dir = Path(data_dir)
    self.zips = self.data_dir / "reports"
    self.zips.mkdir(parents=True, exist_ok=True)
    self._lock = threading.Lock()
    self._db = sqlite3.connect(self.data_dir / "hub.db", check_same_thread=False)
    self._db.row_factory = sqlite3.Row
    columns = ", ".join(
        f"{_quote(c)} INTEGER" if c == "size" else f"{_quote(c)} TEXT" for c in _COLUMNS if c != "report_id"
    )
    with self._lock, self._db:
        self._db.execute(f"CREATE TABLE IF NOT EXISTS reports (report_id TEXT PRIMARY KEY, {columns})")
        for column in ("rig_id", "created_at", "received_at", "status"):
            self._db.execute(f"CREATE INDEX IF NOT EXISTS reports_{column} ON reports ({_quote(column)})")

close

close() -> None

Closes the database.

Source code in src/clabe/hub/_reports.py
def close(self) -> None:
    """Closes the database."""
    with self._lock:
        self._db.close()

has

has(report_id: str) -> bool

Whether report report_id is stored.

Source code in src/clabe/hub/_reports.py
def has(self, report_id: str) -> bool:
    """Whether report ``report_id`` is stored."""
    with self._lock:
        return self._db.execute("SELECT 1 FROM reports WHERE report_id = ?", (report_id,)).fetchone() is not None

add

add(rig_id: str, data: bytes) -> StoredReport | None

Stores a report's zip (its id is that of its report.json); None if it was stored already.

Raises:

Type Description
ValueError

Not a report's zip.

Source code in src/clabe/hub/_reports.py
def add(self, rig_id: str, data: bytes) -> StoredReport | None:
    """Stores a report's zip (its id is that of its ``report.json``); None if it was stored already.

    Raises:
        ValueError: Not a report's zip.
    """
    info = read_report_info(data)
    if not re.fullmatch(REPORT_ID_PATTERN, info.report_id):
        raise ValueError(f"Not a report id: {info.report_id!r}")
    if self.has(info.report_id):
        return None
    path = self.zips / f"{info.report_id}.zip"
    partial = path.with_suffix(".zip.partial")
    partial.write_bytes(data)
    partial.replace(path)
    report = StoredReport(
        **info.model_dump(), rig_id=rig_id, received_at=datetime.datetime.now(datetime.UTC), size=len(data)
    )
    row = self._row(report, path)
    try:
        with self._lock, self._db:
            cursor = self._db.execute(
                f"INSERT OR IGNORE INTO reports ({', '.join(map(_quote, row))}) VALUES ({', '.join('?' * len(row))})",
                list(row.values()),
            )
    except sqlite3.Error:
        path.unlink(missing_ok=True)
        raise
    return report if cursor.rowcount else None

get

get(report_id: str) -> StoredReport | None

Report report_id, if stored.

Source code in src/clabe/hub/_reports.py
def get(self, report_id: str) -> StoredReport | None:
    """Report ``report_id``, if stored."""
    with self._lock:
        row = self._db.execute("SELECT * FROM reports WHERE report_id = ?", (report_id,)).fetchone()
    return self._report(row) if row is not None else None

zip_path

zip_path(report_id: str) -> Path | None

Where report report_id's zip is, if stored.

Source code in src/clabe/hub/_reports.py
def zip_path(self, report_id: str) -> Path | None:
    """Where report ``report_id``'s zip is, if stored."""
    with self._lock:
        row = self._db.execute("SELECT zip_path FROM reports WHERE report_id = ?", (report_id,)).fetchone()
    return Path(row["zip_path"]) if row is not None else None

query

query(
    *,
    rig: str | None = None,
    experiment: str | None = None,
    status: ReportStatus | None = None,
    q: str | None = None,
    sort: ReportSort = "created_at",
    order: Literal["asc", "desc"] = "desc",
    limit: int = 100,
    offset: int = 0,
) -> ReportPage

The reports matching every filter given, sorted, a page at a time.

Parameters:

Name Type Description Default
rig str | None

Only from this rig.

None
experiment str | None

Only of this experiment.

None
status ReportStatus | None

Only in this status.

None
q str | None

Only those with this text (any case) in any text column.

None
sort ReportSort

The column to sort by.

'created_at'
order Literal['asc', 'desc']

asc or desc.

'desc'
limit int

At most this many.

100
offset int

Skipping this many first.

0
Source code in src/clabe/hub/_reports.py
def query(
    self,
    *,
    rig: str | None = None,
    experiment: str | None = None,
    status: ReportStatus | None = None,
    q: str | None = None,
    sort: ReportSort = "created_at",
    order: Literal["asc", "desc"] = "desc",
    limit: int = 100,
    offset: int = 0,
) -> ReportPage:
    """The reports matching every filter given, sorted, a page at a time.

    Args:
        rig: Only from this rig.
        experiment: Only of this experiment.
        status: Only in this status.
        q: Only those with this text (any case) in any text column.
        sort: The column to sort by.
        order: ``asc`` or ``desc``.
        limit: At most this many.
        offset: Skipping this many first.
    """
    where, args = [], []
    for column, value in (("rig_id", rig), ("experiment", experiment), ("status", status)):
        if value is not None:
            where.append(f"{_quote(column)} = ?")
            args.append(value)
    if q:
        pattern = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
        where.append("(" + " OR ".join(f"{_quote(c)} LIKE ? ESCAPE '\\'" for c in _TEXT_COLUMNS) + ")")
        args += [pattern] * len(_TEXT_COLUMNS)
    clause = f" WHERE {' AND '.join(where)}" if where else ""
    if sort not in ReportSort.__args__:  # type: ignore[attr-defined]
        raise ValueError(f"Cannot sort by {sort!r}")
    direction = "ASC" if order == "asc" else "DESC"
    with self._lock:
        total = self._db.execute(f"SELECT COUNT(*) FROM reports{clause}", args).fetchone()[0]
        rows = self._db.execute(
            f"SELECT * FROM reports{clause} ORDER BY {_quote(sort)} {direction}, report_id {direction} "
            "LIMIT ? OFFSET ?",
            [*args, limit, offset],
        ).fetchall()
    return ReportPage(total=total, items=[self._report(r) for r in rows])

set_status

set_status(
    report_id: str, status: ReportStatus
) -> StoredReport | None

Moves report report_id to status; None if it is not stored.

Source code in src/clabe/hub/_reports.py
def set_status(self, report_id: str, status: ReportStatus) -> StoredReport | None:
    """Moves report ``report_id`` to ``status``; None if it is not stored."""
    with self._lock, self._db:
        self._db.execute("UPDATE reports SET status = ? WHERE report_id = ?", (status, report_id))
    return self.get(report_id)

delete

delete(report_ids: list[str]) -> int

Deletes reports (rows and zips); returns how many there were.

Source code in src/clabe/hub/_reports.py
def delete(self, report_ids: list[str]) -> int:
    """Deletes reports (rows and zips); returns how many there were."""
    deleted = 0
    for report_id in report_ids:
        path = self.zip_path(report_id)
        with self._lock, self._db:
            deleted += self._db.execute("DELETE FROM reports WHERE report_id = ?", (report_id,)).rowcount
        if path is not None:
            path.unlink(missing_ok=True)
    return deleted

purge

purge(days: float) -> int

Deletes the reports received more than days days ago; returns how many.

Source code in src/clabe/hub/_reports.py
def purge(self, days: float) -> int:
    """Deletes the reports received more than ``days`` days ago; returns how many."""
    cutoff = _utc(datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=days))
    with self._lock:
        rows = self._db.execute("SELECT report_id FROM reports WHERE received_at < ?", (cutoff,)).fetchall()
    deleted = self.delete([r["report_id"] for r in rows])
    if deleted:
        logger.info("Deleted %s report(s) older than %s days", deleted, days)
    return deleted

counts_by_rig

counts_by_rig() -> dict[str, int]

How many reports are stored for each rig.

Source code in src/clabe/hub/_reports.py
def counts_by_rig(self) -> dict[str, int]:
    """How many reports are stored for each rig."""
    with self._lock:
        rows = self._db.execute("SELECT rig_id, COUNT(*) AS n FROM reports GROUP BY rig_id").fetchall()
    return {r["rig_id"]: r["n"] for r in rows}

StoredReport

Bases: ReportInfo

A report the hub collected: its ReportInfo, the rig it came from, and where it is in its triage.

ZipEntry

Bases: BaseModel

A file in a report's zip.

create_hub_app

create_hub_app(
    fleet: Fleet,
    *,
    token: str | None = None,
    static_dir: Path | None = STATIC_DIR,
    poll: bool = True,
    self_url: str | None = None,
) -> FastAPI

Builds the hub's app.

Parameters:

Name Type Description Default
fleet Fleet

The rigs to follow.

required
token str | None

When set, every API call (the hub's and each rig's) must carry it.

None
static_dir Path | None

The web UI, served at / (the fleet) and under each /rigs/<id>/.

STATIC_DIR
poll bool

Whether to poll the rigs in the background while the app runs.

True
self_url str | None

Where the hub reaches itself (http://127.0.0.1:8080); with it (and the agents extra), an MCP server is served at /mcp (streamable HTTP), acting on every rig through the hub.

None
Source code in src/clabe/hub/_app.py
def create_hub_app(
    fleet: Fleet,
    *,
    token: str | None = None,
    static_dir: Path | None = STATIC_DIR,
    poll: bool = True,
    self_url: str | None = None,
) -> FastAPI:
    """Builds the hub's app.

    Args:
        fleet: The rigs to follow.
        token: When set, every API call (the hub's and each rig's) must carry it.
        static_dir: The web UI, served at ``/`` (the fleet) and under each ``/rigs/<id>/``.
        poll: Whether to poll the rigs in the background while the app runs.
        self_url: Where the hub reaches itself (``http://127.0.0.1:8080``); with it (and the ``agents`` extra), an
            MCP server is served at ``/mcp`` (streamable HTTP), acting on every rig through the hub.
    """

    inspections = InspectCache()
    mcp = _mcp_server(self_url, token)

    @contextlib.asynccontextmanager
    async def lifespan(_: FastAPI) -> AsyncIterator[None]:
        """Polls the rigs (and runs the MCP sessions) while the app serves."""
        if poll:
            fleet.start()
        async with mcp.session_manager.run() if mcp is not None else contextlib.nullcontext():
            yield
        await fleet.stop()
        inspections.close()

    app = FastAPI(
        title="clabe hub API",
        version=__version__,
        description="Follow a fleet of rigs: what each runs, which ones wait for an answer, and each rig's own API "
        "under /rigs/<id>/.",
        lifespan=lifespan,
    )
    app.add_middleware(TokenCookies, token=token)
    app.add_middleware(RequireToken, token=token, prefix="/mcp")
    check = token_check(token)
    api = APIRouter(prefix="/api/hub", dependencies=[Depends(check)])

    @api.get("/rigs", response_model=list[RigStatus])
    def rigs() -> list[RigStatus]:
        """Every rig, as last polled."""
        return fleet.statuses()

    @api.get("/inbox", response_model=list[RigStatus])
    def inbox() -> list[RigStatus]:
        """The rigs whose run waits for an answer, longest-waiting first."""
        return fleet.statuses(fleet.inbox())

    @api.post("/refresh", response_model=list[RigStatus])
    async def refresh() -> list[RigStatus]:
        """Polls every rig now (and collects their reports)."""
        await fleet.poll_once(collect=True)
        return await asyncio.to_thread(fleet.statuses)

    report_routes(api, fleet, inspections)
    app.include_router(api)
    client = httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=None))

    @app.get("/rigs/{rig_id}", include_in_schema=False)
    def rig_root(rig_id: str, request: Request) -> RedirectResponse:
        """A rig's page needs the trailing slash (its links are relative)."""
        query = f"?{request.url.query}" if request.url.query else ""
        return RedirectResponse(f"/rigs/{rig_id}/{query}")

    @app.api_route("/rigs/{rig_id}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"], include_in_schema=False)
    async def proxy(rig_id: str, path: str, request: Request) -> Response:
        """A rig's daemon: its page, its run (``run/``) and their APIs, with the hub's token."""
        rig = fleet.rig(rig_id)
        if rig is None:
            raise HTTPException(status_code=404, detail=f"No rig {rig_id!r}.")
        if "api/" in path:
            await check(request)
        token = rig_token(rig)
        return await forward(
            client, request, f"{rig.url.rstrip('/')}/{path}", token, unreachable=f"{rig_id} is not reachable"
        )

    if mcp is not None:
        app.router.routes.extend(mcp.streamable_http_app(streamable_http_path="/mcp", host="0.0.0.0").routes)

    if static_dir is not None and (static_dir / "index.html").is_file():
        app.mount("/", StaticFiles(directory=static_dir, html=True), name="ui")
    else:

        @app.get("/", response_class=HTMLResponse, include_in_schema=False)
        def placeholder() -> str:
            """A page pointing at the API when the web UI is not built."""
            return '<!doctype html><h1>clabe hub</h1><p>The API is at <a href="/docs">/docs</a>.</p>'

    return app