Errors and Logging#

The exception taxonomy callers branch on, and the logger every connector writes through. The class names and reason codes in osprey_connectors.errors are covered by the package’s compatibility guarantee.

Error classification and handling for the Osprey Framework.

Stability: the exception class names and reason codes defined here are public API. Removing or renaming any of them is a major version bump; adding new ones is a minor version bump.

This module is the connector failure vocabulary.

Three contract roots partition what a connector raises when a call fails, and no class lies under two of them: ChannelError, a failure about one named channel that leaves the connector in place; every single-channel failure (a limits violation, a refused write, a failed write, an address that is not a channel, an unreachable channel) is one, and its channel_address names the channel. ConnectorUnavailableError, the connector itself is gone and its supervisor replaces it. ConnectorInternalError, a connector bug that nothing recovers from. ChannelReadFailedError names several channels and lies under no root.

RefusalReason names why a write was refused, who refused it and what to do about it. ChannelWriteFailedError’s reason codes are the uppercased WriteOutcome words for the outcomes that raise, so the reason a caller branches on and the outcome the result reports are one vocabulary.

The connector-host IPC registry is derived from this module: every class in __all__ under a contract root crosses the process boundary as itself, with its channel, so a public failure needs no registry entry of its own.

osprey_connectors.errors.NOT_A_CHANNEL = 'not a channel of this facility'#

What an address outside the facility is, in every message that names one.

osprey_connectors.errors.RAW_CLIENT_WRITE_MARKER = 'raw client write refused'#

Shared substring of every raw-client-write refusal message. Refusals raised inside an executor subprocess reach the parent only as stderr text, so the parent recognises them by this marker; a test pins the message to it.

exception osprey_connectors.errors.BuildProfileError[source]#

Bases: ConfigurationError

Raised when a build profile is invalid or missing required files.

exception osprey_connectors.errors.ChannelError(channel_address, message)[source]#

Bases: Exception

A failure about one named channel; the connector that raised it stays in place.

channel_address names the channel, in process and across the connector-host boundary alike. No supervisor recovers from a channel error: it is reported against its channel and nothing is restarted. It has no builtin base that another root shares, so no except ConnectionError or except TimeoutError reads it as a lost connector.

commands_fired is set in process by a batch command writer when the batch raised: the addresses, in order, that may have gone out. It is None when no batch writer set it, and it is not a wire field.

commands_fired: list[str] | None = None#
__init__(channel_address, message)[source]#
exception osprey_connectors.errors.ChannelLimitsViolationError(channel_address, value, violation_type, violation_reason, min_value=None, max_value=None, max_step=None, current_value=None)[source]#

Bases: ChannelError

Raised when a channel write violates configured safety limits.

Covers min/max range violations, read-only channel writes, excessive step sizes, and writes to unlisted channels.

__init__(channel_address, value, violation_type, violation_reason, min_value=None, max_value=None, max_step=None, current_value=None)[source]#
exception osprey_connectors.errors.ChannelNotFoundError(channel_address)[source]#

Bases: ChannelError, LookupError

Raised when an address is not a channel of the facility a connector serves.

Only a connector that holds the facility’s whole address set raises it. A connector that cannot tell an unknown name from an unreachable one (a Channel Access search that finds nothing times out) raises ChannelUnreachableError instead. A write to such an address is not raised: it comes back refused with refusal_reason reason.

reason = 'CHANNEL_NOT_FOUND'#

The refusal reason a write to an address outside the facility carries.

__init__(channel_address)[source]#
exception osprey_connectors.errors.ChannelReadFailedError(addresses, message=None, *, causes=None)[source]#

Bases: Exception

Raised when a batch read or a settle’s readback read could not produce a value.

A channel counts as failed when the connector’s result leaves it out (a connector drops a channel whose read raised) or reports it with the value None (the EPICS-family connectors’ answer to a read timeout).

addresses names every failed channel, each once, in the order the caller asked for them, so a caller can report or retry all of them rather than only the first.

causes maps a failed channel to the exception its own read raised, so a timeout, a refused connection and a missing channel stay distinguishable. A failed channel whose read reported no value without raising has no entry.

__init__(addresses, message=None, *, causes=None)[source]#
causes: dict[str, BaseException]#
exception osprey_connectors.errors.ChannelUnreachableError(channel_address, message=None)[source]#

Bases: ChannelError

One channel could not be reached: it was lost, or it did not answer in time.

The connector that raised it is healthy and keeps serving every other channel, so nothing is replaced for it; the failure is that channel’s device, not the control system as a whole. Its text names the address.

__init__(channel_address, message=None)[source]#
exception osprey_connectors.errors.ChannelWriteBlockedError(channel_address, reason, message=None, verdict_reason=None)[source]#

Bases: ChannelError

Raised when a channel write was refused and no value was written.

Distinct from ChannelWriteFailedError, which means the write was attempted and its outcome is a failure rather than a denial.

reason is a RefusalReason member when the reason is a known one, and then names its refuser and remedy. An unknown reason, or no reason at all, is kept as given and names neither: no refuser is guessed.

verdict_reason narrows WRITES_DISABLED to the reason the write verdict gave, a member of osprey_connectors.refusals.REASONS, when it gave one: switch_off, auth_exhausted, auth_range and the rest, so a program branches on the word rather than the message.

classmethod refuser(reason)[source]#

Return who refused a write for reason, or None when no one is known.

Return type:

str | None

classmethod remedy(reason)[source]#

Return the suggestion sentences for reason, or () when none is known.

Return type:

tuple[str, …]

__init__(channel_address, reason, message=None, verdict_reason=None)[source]#
reason: str | None#
exception osprey_connectors.errors.ChannelWriteFailedError(channel_address, reason, message=None, *, outcome=None, value_written=None, observed_value=None)[source]#

Bases: ChannelError

Raised when a channel write was attempted but was not confirmed.

The control system was asked to write but the write failed, the channel now holds a different value, or the write was sent but not acknowledged in time or the confirming re-read itself failed. Distinct from ChannelWriteBlockedError (a refusal — no value was written). A scan consumer must abort on this.

reason is one of: “FAILED”, “MISMATCH”, “UNCONFIRMED” — the WriteOutcome words that raise. All three are protocol-neutral on purpose: the same codes describe an EPICS, DOOCS, or simulated write.

outcome, value_written and observed_value carry the detail the result held, so a caller that only sees the exception can still say what was sent and what the channel holds. outcome is a WriteOutcome member on either side of the connector-host boundary: the plain string the wire carries is coerced on construction, as ChannelWriteResult coerces its own.

__init__(channel_address, reason, message=None, *, outcome=None, value_written=None, observed_value=None)[source]#
exception osprey_connectors.errors.ClientLibraryRefusedError(*, package=None, library=None)[source]#

Bases: RuntimeError

Raised when a process that may hold no control-system client loads one.

reason is “RAW_CLIENT_IMPORT”: user code imported a control-system client package, or loaded a client shared library, in a process whose only route to the machine is osprey.runtime. Nothing was loaded and no channel was touched. package names the refused top-level package and library the refused shared library; one of the two is set.

A RuntimeError rather than an ImportError: code that treats a missing optional client as absent (except ImportError) must not read a refusal as “not installed” and carry on down another route.

MARKER = 'control-system client refused'#

Shared substring of every client refusal message.

__init__(*, package=None, library=None)[source]#
exception osprey_connectors.errors.ConfigurationError[source]#

Bases: Exception

Exception for configuration-related errors.

Raised when configuration files are invalid, missing required settings, or contain incompatible values that prevent proper system operation.

exception osprey_connectors.errors.ConnectorInternalError(message, class_tag=None)[source]#

Bases: RuntimeError

Raised in the parent for something the connector-host child sent outside the contract.

It has two sources, and both fail one call only. A connector bug: the child raised an exception the IPC registry does not carry typed, and the message carries the child’s repr. An unrebuildable reply: the child answered with a value the parent cannot rebuild into its declared type. Neither is a reachability answer, and nothing about the connector or the child is implied, so no supervisor recovers from it.

It is a RuntimeError and never a ConnectionError or OSError, so that no except ConnectionError or except OSError reads a connector bug as an unreachable control system.

class_tag names the class the child sent: the exception’s class for a connector bug, the value’s class for an unrebuildable reply.

__init__(message, class_tag=None)[source]#
exception osprey_connectors.errors.ConnectorUnavailableError(message, recovery=())[source]#

Bases: ConnectionError

The connector itself is gone: its transport, context or process is lost.

Every channel it serves fails alike until it is replaced, and the supervisor that owns the connector’s lifetime replaces it at most once per instance. recovery is what that supervisor did, one {"action", "text"} record per step, set by the supervisor and by nothing else; it is empty until a supervisor has acted.

__init__(message, recovery=())[source]#
recovery: tuple[RecoveryRecord, ...]#
class osprey_connectors.errors.RecoveryRecord[source]#

Bases: TypedDict

One thing a supervisor did about a failure, as a failure’s recovery carries it.

action is the word naming the step (RecoveryAction), text the sentence an operator reads.

action: str#
text: str#
class osprey_connectors.errors.RefusalReason(value)[source]#

Bases: StrEnum

Why a write was refused, with who refused it and what to do about it.

Each member’s value is the reason word a result and an exception carry. refuser names who refused a write for the reason, and is None for CHANNEL_NOT_FOUND: nothing was denied, the address is not a channel. remedy holds the reason’s own suggestion sentences, in the order a message lists them; it is empty for CHANNEL_NOT_FOUND, whose answer is rendered as “not a channel”.

RAW_CLIENT_WRITE means user code called a control-system client library’s put directly instead of going through osprey.runtime.write_channel; nothing was sent. CONTROL_SYSTEM_REFUSED is the one reason under which the write was sent: the control system was asked and denied it. BATCH_REFUSED is a write of a batch that passed every check of its own and was not sent because another write of the batch was refused.

refuser: str | None#
remedy: tuple[str, ...]#
WRITES_DISABLED = 'WRITES_DISABLED'#
LIMITS = 'LIMITS'#
VALIDATION_ERROR = 'VALIDATION_ERROR'#
CONTROL_SYSTEM_REFUSED = 'CONTROL_SYSTEM_REFUSED'#
RAW_CLIENT_WRITE = 'RAW_CLIENT_WRITE'#
BATCH_REFUSED = 'BATCH_REFUSED'#
CHANNEL_NOT_FOUND = 'CHANNEL_NOT_FOUND'#
exception osprey_connectors.errors.RegistryError[source]#

Bases: Exception

Exception for registry-related errors.

Raised when issues occur with component registration, lookup, or management within the framework’s registry system.

osprey_connectors.errors.raw_client_write_message(address)[source]#

Return the refusal text for a direct client-library write to address.

address may be "<unknown>" when the refused call does not expose a channel name (a low-level handle put, for instance).

Return type:

str

Component Logger Framework

Provides colored logging for Osprey and application components with: - Unified API for all components (capabilities, infrastructure, pipelines) - Rich terminal output on stderr with component-specific colors - Graceful fallbacks when configuration is unavailable - Simple, clear interface

Handler setup is explicit and separate from logger lookup. Entry points — the CLI, service startups, the dispatch worker, MCP servers — call configure_logging() once; everything else just calls get_logger(), which has no global side effects.

Usage:

# Entry point, once at startup configure_logging()

# Module-level logger = get_logger(“orchestrator”) logger.key_info(“Starting orchestration”)

logger = get_logger(“data_processor”) logger.info(“Processing data”) logger.debug(“Detailed trace”) logger.success(“Operation completed”) logger.warning(“Something to note”) logger.error(“Something went wrong”) logger.timing(“Execution took 2.5 seconds”) logger.approval(“Waiting for user approval”)

# Custom loggers with explicit parameters logger = get_logger(name=”custom_component”, color=”blue”)

class osprey_connectors.logger.ComponentLogger(base_logger, component_name, color='white', state=None)[source]#

Bases: object

Rich-formatted logger for Osprey and application components with color coding and message hierarchy.

Message Types: - status: High-level status updates - key_info: Important operational information - info: Normal operational messages - debug: Detailed tracing information - warning: Warning messages - error: Error messages - success: Success messages - timing: Timing information - approval: Approval messages - resume: Resume messages

Every emitted record carries the name of the method that produced it as the osprey_intent attribute, so handlers and filters can tell intents apart where the level cannot (info and key_info both log at INFO). It is metadata only: no level is remapped and no formatter reads it.

Initialize component logger.

Parameters:
  • base_logger (Logger) – Underlying Python logger

  • component_name (str) – Name of the component (e.g., ‘data_analysis’, ‘router’, ‘mongo’)

  • color (str) – Rich color name for this component

  • state (object) – Optional state for context (unused, kept for API compat)

__init__(base_logger, component_name, color='white', state=None)[source]#

Initialize component logger.

Parameters:
  • base_logger (Logger) – Underlying Python logger

  • component_name (str) – Name of the component (e.g., ‘data_analysis’, ‘router’, ‘mongo’)

  • color (str) – Rich color name for this component

  • state (object) – Optional state for context (unused, kept for API compat)

status(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Status update — high-level progress messages.

key_info(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Important operational information.

info(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Normal operational messages.

debug(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Debug-level messages.

warning(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Warning messages.

error(message, *args, exc_info=False, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Error messages.

success(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Success messages.

timing(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Timing information.

approval(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Approval messages.

resume(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Resume messages.

critical(message, *args, exc_info=None, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Critical error messages.

exception(message, *args, stack_info=False, stacklevel=1, extra=None, **other)[source]#

Exception with traceback.

property level: int#
property name: str#
setLevel(level)[source]#
isEnabledFor(level)[source]#
Return type:

bool

osprey_connectors.logger.configure_logging(level=logging.INFO)[source]#

Configure logging for an Osprey entry point.

Call this once, explicitly, from every entry point (CLI main, service startups, the dispatch worker, MCP server __main__). Library and import paths must never call it — importing Osprey leaves logging untouched.

The configuration is strictly additive: it installs the Osprey RichHandler only if the root logger has no RichHandler yet, and it never removes or clears handlers it did not install. Handlers owned by someone else — caplog’s capture handler, a host application’s own handlers — survive. Calling it repeatedly is a no-op beyond re-applying the level.

Parameters:

level (int) – Root logger level.

osprey_connectors.logger.get_logger(component_name=None, level=logging.INFO, *, state=None, name=None, color=None)[source]#

Get a unified logger for CLI logging.

This is a pure lookup: it mutates no global logging state. Handler and level configuration belongs to configure_logging(), which entry points call once at startup. A module that only imports Osprey therefore leaves the host application’s logging exactly as it found it.

Name the logger by its component (the recommended form), or give name and color directly for a custom or module-level logger.

Parameters:
  • component_name (str | None) – Component name (e.g., ‘orchestrator’, ‘data_analysis’)

  • level (int) – Accepted for backwards compatibility and ignored — set levels through configure_logging() or on the returned logger.

  • state (object) – Optional state for context

  • name (str | None) – Direct logger name (keyword-only)

  • color (str | None) – Direct color specification (keyword-only)

Returns:

ComponentLogger instance

Return type:

ComponentLogger

Examples

# Module-level
logger = get_logger("orchestrator")
logger.info("Planning started")

# Custom logger
logger = get_logger(name="test_logger", color="blue")
osprey_connectors.logger.set_handler_console(console)[source]#

Render root-logger records through console from now on.

For entry points that already own a console of their own — the CLI owns the themed, terminal-sized stderr console every command prints through — so that logging and printed output share one renderer instead of interleaving two consoles with different widths on the same stream.

Deliberately separate from configure_logging(), which stays untouched: the 15+ non-CLI entry points and external consumers of this package call that and must keep the console it has always built for them.

Repointing an existing handler rather than rebuilding it keeps this safe to call any number of times in one process — CLI invocations repeat inside a single test process — with no handler ever stacking on the root logger.

Parameters:

console (Console) – Console the Rich handler should render through.

Returns:

The handler that was repointed, so a caller can go on to configure that same instance; None if the root logger has no RichHandler (a caller that has not called configure_logging() yet).

Return type:

RichHandler | None

Temporary suppression of a logger’s low-level messages.

quiet_logger() raises one or more loggers to WARNING for the duration of a with block and restores their levels afterwards.

osprey_connectors.log_filter.quiet_logger(logger_name)[source]#

Context manager to temporarily suppress INFO-level messages from logger(s).

This is a convenience wrapper around _suppress_logger_level() that specifically suppresses INFO and DEBUG messages while preserving WARNING, ERROR, and CRITICAL. This is the most common use case for “quiet” operations.

Parameters:

logger_name (str | list[str]) – Name of logger(s) to quiet. Can be a single string or list of strings for multiple loggers.

Yields:

Dictionary mapping logger names to their original levels

Return type:

Iterator[dict[str, int]]

Examples

Quiet a single logger:

>>> with quiet_logger('registry'):
...     initialize_registry()  # No INFO messages shown

Quiet multiple loggers:

>>> with quiet_logger(['registry', 'DATABASE']):
...     do_something()

Note

This raises the level to logging.WARNING for the block.