Lifecycle & degradation

DeskBot's lifecycle package (robot.lifecycle) provides the async-safe startup/shutdown controller and the graceful degradation registry that keeps the robot running even when hardware fails.

See also the Lifecycle architecture for the design rationale and data flow.


Lifecycle

Lifecycle is the only place that owns the root task group and the event-bus subscription. Components subscribe to events in startup and unsubscribe in shutdown; the manager guarantees both are called exactly once and all errors are surfaced.

States

stateDiagram-v2 NEW --> STARTING STARTING --> RUNNING RUNNING --> STOPPING STOPPING --> STOPPED

Hooks

Hook When Purpose
on_startup Application starts Subscribe to events, start background tasks
on_shutdown Application stops Unsubscribe, cancel tasks, close resources

Hooks are async callables. The manager runs all startup hooks, then all shutdown hooks in reverse order. If any hook raises, the error is logged and the remaining hooks still run.

Usage

from robot.lifecycle import Lifecycle

lifecycle = Lifecycle(bus=event_bus)
lifecycle.add_startup(my_component.start)
lifecycle.add_shutdown(my_component.stop)

async with lifecycle.running() as task_group:
    await anyio.sleep_forever()

Graceful degradation

When a hardware component (display, servos, microphone, etc.) fails to initialise, the application falls back to a mock implementation and records the failure in the DegradationRegistry.

Design principles

  • The robot never crashes due to a hardware failure.
  • Every component has a mock fallback.
  • Degradation entries are logged at WARNING level, not ERROR.
  • The registry is accessible via the API even in ERROR state.

DegradationEntry

Each entry records:

Field Description
component Which component degraded (e.g. "display", "servos")
status "ok", "degraded", or "failed"
original_backend The configured backend that failed
fallback_backend The mock/no-op backend used instead
error The error message (if any)

safe_init

safe_init() is the helper that wraps factory construction with automatic fallback:

from robot.lifecycle import safe_init

display = safe_init(
    factory=lambda: GC9A01Display(...),
    component="display",
    fallback=MockDisplay,
    registry=degradation_registry,
    original_backend="gc9a01",
    fallback_backend="mock",
)

If the factory raises, safe_init logs the error, records a degradation entry, and returns the fallback instance instead. The robot continues operating with the mock — it just won't have a real display.

Health endpoint

The GET /api/v1/health endpoint exposes the degradation registry so external monitoring tools can see which components are running in degraded mode:

{
  "status": "degraded",
  "components": [
    {"component": "display", "status": "degraded", "original": "gc9a01", "fallback": "mock"}
  ]
}

API reference

robot.lifecycle

Async-safe application lifecycle manager.

The lifecycle is the only place that owns the root task group and the event-bus subscription. Components subscribe to events in startup and unsubscribe in shutdown; the manager guarantees both are called exactly once and all errors are surfaced.

DegradationEntry dataclass

One recorded component degradation event.

Source code in src/robot/lifecycle/degradation.py
@dataclass(slots=True)
class DegradationEntry:
    """One recorded component degradation event."""

    component: str
    status: Status
    original_backend: str
    fallback_backend: str
    error: str | None = None
    timestamp: float = field(default_factory=time.time)

DegradationRegistry

Tracks component degradation across the application.

Thread-safe for reads: :meth:report returns a snapshot that will not mutate under the caller. Concurrent :meth:record calls are safe because Python's GIL serialises list appends.

Source code in src/robot/lifecycle/degradation.py
class DegradationRegistry:
    """Tracks component degradation across the application.

    Thread-safe for reads: :meth:`report` returns a snapshot that will
    not mutate under the caller.  Concurrent :meth:`record` calls are
    safe because Python's GIL serialises list appends.
    """

    def __init__(self) -> None:
        self._entries: list[DegradationEntry] = []
        self._lock = threading.Lock()

    def record(self, entry: DegradationEntry) -> None:
        """Record a degradation entry and log at WARNING level."""
        with self._lock:
            self._entries.append(entry)
        if entry.status == "ok":
            _log.info(
                "component.ok",
                component=entry.component,
                backend=entry.original_backend,
            )
        else:
            _log.warning(
                "component.fallback",
                component=entry.component,
                original=entry.original_backend,
                fallback=entry.fallback_backend,
                error=entry.error,
            )

    def report(self) -> list[DegradationEntry]:
        """Return a snapshot of all recorded degradation entries."""
        with self._lock:
            return list(self._entries)

    def summary(self) -> str:
        """Return a human-readable one-line summary of degradation status."""
        entries = self.report()
        if not entries:
            return "all components ok"
        degraded = [e for e in entries if e.status != "ok"]
        if not degraded:
            return "all components ok"
        parts = [f"{e.component}->{e.fallback_backend}" for e in degraded]
        return "degraded: " + ", ".join(parts)

    def overall_status(self) -> Status:
        """Return the worst status across all entries.

        Returns ``"ok"`` if no entries have been recorded yet.
        """
        if not self._entries:
            return "ok"
        if any(e.status == "failed" for e in self._entries):
            return "failed"
        if any(e.status == "degraded" for e in self._entries):
            return "degraded"
        return "ok"

    def to_dict(self) -> dict[str, object]:
        """Return a JSON-serialisable dict for the health endpoint."""
        entries = self.report()
        components: dict[str, dict[str, str]] = {}
        for entry in entries:
            info: dict[str, str] = {
                "status": entry.status,
                "backend": (
                    entry.original_backend if entry.status == "ok" else entry.fallback_backend
                ),
            }
            if entry.original_backend != entry.fallback_backend:
                info["original"] = entry.original_backend
            if entry.error is not None:
                info["error"] = entry.error
            components[entry.component] = info
        return {
            "status": self.overall_status(),
            "components": components,
        }

overall_status()

Return the worst status across all entries.

Returns "ok" if no entries have been recorded yet.

Source code in src/robot/lifecycle/degradation.py
def overall_status(self) -> Status:
    """Return the worst status across all entries.

    Returns ``"ok"`` if no entries have been recorded yet.
    """
    if not self._entries:
        return "ok"
    if any(e.status == "failed" for e in self._entries):
        return "failed"
    if any(e.status == "degraded" for e in self._entries):
        return "degraded"
    return "ok"

record(entry)

Record a degradation entry and log at WARNING level.

Source code in src/robot/lifecycle/degradation.py
def record(self, entry: DegradationEntry) -> None:
    """Record a degradation entry and log at WARNING level."""
    with self._lock:
        self._entries.append(entry)
    if entry.status == "ok":
        _log.info(
            "component.ok",
            component=entry.component,
            backend=entry.original_backend,
        )
    else:
        _log.warning(
            "component.fallback",
            component=entry.component,
            original=entry.original_backend,
            fallback=entry.fallback_backend,
            error=entry.error,
        )

report()

Return a snapshot of all recorded degradation entries.

Source code in src/robot/lifecycle/degradation.py
def report(self) -> list[DegradationEntry]:
    """Return a snapshot of all recorded degradation entries."""
    with self._lock:
        return list(self._entries)

summary()

Return a human-readable one-line summary of degradation status.

Source code in src/robot/lifecycle/degradation.py
def summary(self) -> str:
    """Return a human-readable one-line summary of degradation status."""
    entries = self.report()
    if not entries:
        return "all components ok"
    degraded = [e for e in entries if e.status != "ok"]
    if not degraded:
        return "all components ok"
    parts = [f"{e.component}->{e.fallback_backend}" for e in degraded]
    return "degraded: " + ", ".join(parts)

to_dict()

Return a JSON-serialisable dict for the health endpoint.

Source code in src/robot/lifecycle/degradation.py
def to_dict(self) -> dict[str, object]:
    """Return a JSON-serialisable dict for the health endpoint."""
    entries = self.report()
    components: dict[str, dict[str, str]] = {}
    for entry in entries:
        info: dict[str, str] = {
            "status": entry.status,
            "backend": (
                entry.original_backend if entry.status == "ok" else entry.fallback_backend
            ),
        }
        if entry.original_backend != entry.fallback_backend:
            info["original"] = entry.original_backend
        if entry.error is not None:
            info["error"] = entry.error
        components[entry.component] = info
    return {
        "status": self.overall_status(),
        "components": components,
    }

Lifecycle

Cooperative startup/shutdown controller.

Example

lifecycle = Lifecycle(bus=event_bus) lifecycle.add_startup(my_component.start) async with lifecycle.running() as task_group: ... await anyio.sleep_forever()

Source code in src/robot/lifecycle/_core.py
class Lifecycle:
    """Cooperative startup/shutdown controller.

    Example
    -------
    >>> lifecycle = Lifecycle(bus=event_bus)
    >>> lifecycle.add_startup(my_component.start)
    >>> async with lifecycle.running() as task_group:
    ...     await anyio.sleep_forever()
    """

    def __init__(self, bus: EventBus) -> None:
        self._bus = bus
        self._state: LifecycleState = LifecycleState.NEW
        self._startup_hooks: list[StartupHook] = []
        self._shutdown_hooks: list[ShutdownHook] = []
        self._task_group: anyio.abc.TaskGroup | None = None

    # ------------------------------------------------------------------ state
    @property
    def state(self) -> LifecycleState:
        return self._state

    @property
    def is_running(self) -> bool:
        return self._state is LifecycleState.RUNNING

    # ------------------------------------------------------------------ hooks
    def add_startup(self, hook: StartupHook) -> None:
        if self._state is not LifecycleState.NEW:
            raise LifecycleError("cannot add startup hooks after startup")
        self._startup_hooks.append(hook)

    def add_shutdown(self, hook: ShutdownHook) -> None:
        if self._state is not LifecycleState.STOPPED:
            self._shutdown_hooks.append(hook)

    # ------------------------------------------------------------------ run
    @contextlib.asynccontextmanager
    async def running(self) -> AsyncIterator[anyio.abc.TaskGroup]:
        """Run the application inside an ``anyio`` task group.

        Yields the task group so callers can spawn long-running services
        (HTTP server, audio loop, etc.) alongside the lifecycle.
        """
        if self._state is not LifecycleState.NEW:
            raise LifecycleError(f"cannot start from state {self._state}")

        async with anyio.create_task_group() as tg:
            self._task_group = tg
            self._state = LifecycleState.STARTING
            await self._run_hooks(self._startup_hooks, "startup")
            self._state = LifecycleState.RUNNING
            _log.info("lifecycle.running")
            try:
                yield tg
            finally:
                self._state = LifecycleState.STOPPING
                await self._run_hooks(self._shutdown_hooks, "shutdown")
                self._state = LifecycleState.STOPPED
                self._task_group = None
                _log.info("lifecycle.stopped")

    # ------------------------------------------------------------------ misc
    async def _run_hooks(self, hooks: list[Callable[[], Awaitable[None]]], phase: str) -> None:
        for hook in hooks:
            try:
                await hook()
            except Exception:
                _log.exception("lifecycle.hook_failed", phase=phase, hook=hook)
                raise

running() async

Run the application inside an anyio task group.

Yields the task group so callers can spawn long-running services (HTTP server, audio loop, etc.) alongside the lifecycle.

Source code in src/robot/lifecycle/_core.py
@contextlib.asynccontextmanager
async def running(self) -> AsyncIterator[anyio.abc.TaskGroup]:
    """Run the application inside an ``anyio`` task group.

    Yields the task group so callers can spawn long-running services
    (HTTP server, audio loop, etc.) alongside the lifecycle.
    """
    if self._state is not LifecycleState.NEW:
        raise LifecycleError(f"cannot start from state {self._state}")

    async with anyio.create_task_group() as tg:
        self._task_group = tg
        self._state = LifecycleState.STARTING
        await self._run_hooks(self._startup_hooks, "startup")
        self._state = LifecycleState.RUNNING
        _log.info("lifecycle.running")
        try:
            yield tg
        finally:
            self._state = LifecycleState.STOPPING
            await self._run_hooks(self._shutdown_hooks, "shutdown")
            self._state = LifecycleState.STOPPED
            self._task_group = None
            _log.info("lifecycle.stopped")

LifecycleHooks dataclass

Container for startup and shutdown callbacks.

Source code in src/robot/lifecycle/_core.py
@dataclass(slots=True, frozen=True)
class LifecycleHooks:
    """Container for startup and shutdown callbacks."""

    on_startup: tuple[StartupHook, ...] = ()
    on_shutdown: tuple[ShutdownHook, ...] = ()

LifecycleState

Bases: str, Enum

High-level state of the application lifecycle.

Source code in src/robot/lifecycle/_core.py
class LifecycleState(str, Enum):
    """High-level state of the application lifecycle."""

    NEW = "new"
    STARTING = "starting"
    RUNNING = "running"
    STOPPING = "stopping"
    STOPPED = "stopped"

safe_init(factory, component, fallback, registry, *, original_backend, fallback_backend='mock')

Try to create a component; fall back to fallback on failure.

Parameters

factory: Callable that returns the real component. May raise :class:ImportError or :class:RuntimeError (or any exception) if the hardware is unavailable. component: Human-readable component name (e.g. "display"). fallback: Callable that returns the mock fallback instance. registry: :class:DegradationRegistry to record the outcome. original_backend: Name of the backend that was attempted (e.g. "gc9a01"). fallback_backend: Name of the fallback backend (defaults to "mock").

Returns

The real instance if factory succeeds, otherwise the mock.

Source code in src/robot/lifecycle/degradation.py
def safe_init[T](
    factory: Callable[[], T],
    component: str,
    fallback: Callable[[], T],
    registry: DegradationRegistry,
    *,
    original_backend: str,
    fallback_backend: str = "mock",
) -> T:
    """Try to create a component; fall back to *fallback* on failure.

    Parameters
    ----------
    factory:
        Callable that returns the real component.  May raise
        :class:`ImportError` or :class:`RuntimeError` (or any
        exception) if the hardware is unavailable.
    component:
        Human-readable component name (e.g. ``"display"``).
    fallback:
        Callable that returns the mock fallback instance.
    registry:
        :class:`DegradationRegistry` to record the outcome.
    original_backend:
        Name of the backend that was attempted (e.g. ``"gc9a01"``).
    fallback_backend:
        Name of the fallback backend (defaults to ``"mock"``).

    Returns
    -------
    The real instance if *factory* succeeds, otherwise the mock.
    """
    try:
        instance = factory()
        registry.record(
            DegradationEntry(
                component=component,
                status="ok",
                original_backend=original_backend,
                fallback_backend=original_backend,
            )
        )
        return instance
    except Exception as exc:
        _log.warning(
            "component.init_fallback",
            component=component,
            original=original_backend,
            fallback=fallback_backend,
            error=str(exc),
        )
        registry.record(
            DegradationEntry(
                component=component,
                status="degraded",
                original_backend=original_backend,
                fallback_backend=fallback_backend,
                error=str(exc),
            )
        )
        return fallback()