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:
ConfigurationErrorRaised when a build profile is invalid or missing required files.
- exception osprey_connectors.errors.ChannelError(channel_address, message)[source]#
Bases:
ExceptionA failure about one named channel; the connector that raised it stays in place.
channel_addressnames 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 noexcept ConnectionErrororexcept TimeoutErrorreads it as a lost connector.commands_firedis set in process by a batch command writer when the batch raised: the addresses, in order, that may have gone out. It isNonewhen no batch writer set it, and it is not a wire field.- commands_fired: list[str] | None = None#
- 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:
ChannelErrorRaised 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.
- exception osprey_connectors.errors.ChannelNotFoundError(channel_address)[source]#
Bases:
ChannelError,LookupErrorRaised 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
ChannelUnreachableErrorinstead. A write to such an address is not raised: it comes backrefusedwithrefusal_reasonreason.- reason = 'CHANNEL_NOT_FOUND'#
The refusal reason a write to an address outside the facility carries.
- exception osprey_connectors.errors.ChannelReadFailedError(addresses, message=None, *, causes=None)[source]#
Bases:
ExceptionRaised 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).addressesnames 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.causesmaps 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.- causes: dict[str, BaseException]#
- exception osprey_connectors.errors.ChannelUnreachableError(channel_address, message=None)[source]#
Bases:
ChannelErrorOne 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.
- exception osprey_connectors.errors.ChannelWriteBlockedError(channel_address, reason, message=None, verdict_reason=None)[source]#
Bases:
ChannelErrorRaised 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.
reasonis aRefusalReasonmember 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_reasonnarrowsWRITES_DISABLEDto the reason the write verdict gave, a member ofosprey_connectors.refusals.REASONS, when it gave one:switch_off,auth_exhausted,auth_rangeand 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, …]
- reason: str | None#
- exception osprey_connectors.errors.ChannelWriteFailedError(channel_address, reason, message=None, *, outcome=None, value_written=None, observed_value=None)[source]#
Bases:
ChannelErrorRaised 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
WriteOutcomewords that raise. All three are protocol-neutral on purpose: the same codes describe an EPICS, DOOCS, or simulated write.outcome,value_writtenandobserved_valuecarry the detail the result held, so a caller that only sees the exception can still say what was sent and what the channel holds.outcomeis aWriteOutcomemember on either side of the connector-host boundary: the plain string the wire carries is coerced on construction, asChannelWriteResultcoerces its own.
- exception osprey_connectors.errors.ClientLibraryRefusedError(*, package=None, library=None)[source]#
Bases:
RuntimeErrorRaised 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.packagenames the refused top-level package andlibrarythe refused shared library; one of the two is set.A
RuntimeErrorrather than anImportError: 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.
- exception osprey_connectors.errors.ConfigurationError[source]#
Bases:
ExceptionException 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:
RuntimeErrorRaised 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
RuntimeErrorand never aConnectionErrororOSError, so that noexcept ConnectionErrororexcept OSErrorreads a connector bug as an unreachable control system.class_tagnames the class the child sent: the exception’s class for a connector bug, the value’s class for an unrebuildable reply.
Bases:
ConnectionErrorThe 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.
recoveryis 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.
- class osprey_connectors.errors.RecoveryRecord[source]#
Bases:
TypedDictOne thing a supervisor did about a failure, as a failure’s
recoverycarries it.actionis the word naming the step (RecoveryAction),textthe sentence an operator reads.- action: str#
- text: str#
- class osprey_connectors.errors.RefusalReason(value)[source]#
Bases:
StrEnumWhy 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.
refusernames who refused a write for the reason, and isNoneforCHANNEL_NOT_FOUND: nothing was denied, the address is not a channel.remedyholds the reason’s own suggestion sentences, in the order a message lists them; it is empty forCHANNEL_NOT_FOUND, whose answer is rendered as “not a channel”.RAW_CLIENT_WRITEmeans user code called a control-system client library’s put directly instead of going throughosprey.runtime.write_channel; nothing was sent.CONTROL_SYSTEM_REFUSEDis the one reason under which the write was sent: the control system was asked and denied it.BATCH_REFUSEDis 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:
ExceptionException 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.addressmay 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:
objectRich-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_intentattribute, so handlers and filters can tell intents apart where the level cannot (infoandkey_infoboth 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#
- 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
RichHandleronly if the root logger has noRichHandleryet, 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
nameandcolordirectly 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:
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
consolefrom 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;
Noneif the root logger has noRichHandler(a caller that has not calledconfigure_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.WARNINGfor the block.