Connector Contracts#

The two interfaces every connector implements, and the door a connector opens around its own write. What a conforming connector must do is described in Connector Contracts; these are the classes and functions that carry it.

The control-system connector contract.

ControlSystemConnector and the value, metadata and write-result models it returns, the write-outcome vocabulary, and the limits validator every connector checks a write against. A new control system subclasses the connector here; a configured one is built through osprey_connectors.factory.ConnectorFactory from its type name. The concrete connectors are the _*_connector modules beside this one.

The limits validator’s names are resolved on access (PEP 562). Every import of osprey_connectors.control_system.write_door runs this file first, and the raw-put guard reads the door inside executor sandboxes and notebook kernels; importing the validator here would load its logging and YAML stack into every one of them, and importing the EPICS connector for its stale hold-down would load its Channel Access stack.

class osprey_connectors.control_system.ChannelLimitsConfig(channel_address, min_value=None, max_value=None, max_step=None, *, writable)[source]#

Bases: object

Configuration for a single channel’s limits.

channel_address: str#
min_value: float | None = None#
max_value: float | None = None#
max_step: float | None = None#
writable: bool#
__init__(channel_address, min_value=None, max_value=None, max_step=None, *, writable)#
class osprey_connectors.control_system.ChannelMetadata(units='', precision=None, alarm_status=None, alarm_severity=None, timestamp=None, description=None, display_low=None, display_high=None, enum_labels=None, enum_label=None, raw_metadata=<factory>, control_low=None, control_high=None, warning_low=None, warning_high=None, alarm_low=None, alarm_high=None, writable=None)[source]#

Bases: object

Metadata a control system reports about one of its channels.

display_low / display_high are the range the control system suggests for DISPLAYING this channel (EPICS LOPR/HOPR and their equivalents). They are deliberately NOT named min_value / max_value: those belong to ChannelLimitsConfig and are the bounds OSPREY refuses to write past. Only the latter is enforced — a value inside the display range can still be refused, and a connector that reports no display range constrains nothing.

enum_labels / enum_label are present only for enum-typed records (EPICS mbbi/mbbo/bi/bo, PVAccess NTEnum, and their equivalents elsewhere) and are None on every other channel. They are the readable half of an enum reading: ChannelValue.value stays the integer index — one machine-readable type across every protocol — and the label for that index rides here, resolved at read time. Either may be None even on an enum channel: a control system reports the label list only when it has one, and an index outside it resolves to nothing.

enum_labels is a list rather than a tuple because that is what survives the connector-host IPC seam: osprey_connectors.ipc._frames encodes sequences as JSON arrays and decodes them as lists, so a tuple set here would compare unequal to the same field read through a proxy.

control_low / control_high (EPICS DRVL/DRVH), warning_low / warning_high (LOW/HIGH) and alarm_low / alarm_high (LOLO/HIHI) are the remaining limit pairs a control system reports. Like the display range they describe the channel; none of them is a write bound OSPREY enforces. writable is this client’s access right on the channel (EPICS CA write access) — not the user’s tier — and None where the control system does not report one.

Every limit pair, the display range included, passes through normalise_limit_pair() on construction: a missing, non-numeric or non-finite bound becomes None, and a pair whose low is not below its high (EPICS reports an unset range as 0/0) becomes None on both sides. The normalisation is idempotent, so a value decoded on the far side of the connector-host IPC seam — which re-runs __post_init__ — is unchanged.

units: str = ''#
precision: int | None = None#
alarm_status: str | None = None#

Alarm name reported for the reading, e.g. “NO_ALARM”/”HIHI”; None if not reported.

alarm_severity: int | None = None#

0 healthy, higher is worse; None means “not reported”, which stays distinct from a reported healthy value (alarm_severity=0) — the same convention as ChannelWriteResult.alarm_severity.

Type:

Alarm severity

timestamp: datetime | None = None#
description: str | None = None#
display_low: float | None = None#
display_high: float | None = None#
enum_labels: list[str] | None = None#

Every state this enum-typed channel can report, in index order; None off enums.

enum_label: str | None = None#

The label for the value of THIS reading; None off enums and when unresolvable.

raw_metadata: dict[str, Any] | None#
control_low: float | None = None#

Drive range (EPICS DRVL/DRVH); None when unreported or not a valid range.

control_high: float | None = None#
warning_low: float | None = None#

Minor-alarm range (EPICS LOW/HIGH); None when unreported or not a valid range.

warning_high: float | None = None#
alarm_low: float | None = None#

Major-alarm range (EPICS LOLO/HIHI); None when unreported or not a valid range.

alarm_high: float | None = None#
writable: bool | None = None#

This client’s write access to the channel; None when the control system does not say.

__post_init__()[source]#

Ensure raw_metadata is a dict and normalise the limits and writable.

__init__(units='', precision=None, alarm_status=None, alarm_severity=None, timestamp=None, description=None, display_low=None, display_high=None, enum_labels=None, enum_label=None, raw_metadata=<factory>, control_low=None, control_high=None, warning_low=None, warning_high=None, alarm_low=None, alarm_high=None, writable=None)#
class osprey_connectors.control_system.ChannelValue(value, timestamp, metadata=<factory>)[source]#

Bases: object

Value of a control system channel with metadata.

value: Any#
timestamp: datetime#
metadata: ChannelMetadata#
__init__(value, timestamp, metadata=<factory>)#
class osprey_connectors.control_system.ChannelWriteResult(channel_address, value_written, outcome, refusal_reason=None, error_message=None, observed_value=None, alarm_status=None, alarm_severity=None, notes=None, verdict_reason=None)[source]#

Bases: object

What became of one channel write, and what the channel was seen to hold.

The control-system-agnostic result type returned by every connector. outcome is the single owned verdict (see WriteOutcome), set by the connector that performed the write; no consumer re-derives one.

error_message is set if and only if outcome is one of refused, failed or unconfirmed — the three words that carry something the operator has to be told. A mismatch needs no message: both numbers are on the result already, in value_written and observed_value. Construction enforces it: a result that breaks it raises ValueError.

notes is display-only text (“observed 2.4, sent 2.5”, “cannot be compared”). No consumer reads it, and nothing classifies a write by parsing it.

refusal_reason is the RefusalReason that says why, and who, refused; it is set if and only if the outcome is refused. Construction enforces it too: a refused result with no reason or an unknown one, or a reason on any other outcome, raises ValueError. verdict_reason narrows a WRITES_DISABLED refusal to the reason the write verdict gave, a member of osprey_connectors.refusals.REASONS — switch_off, auth_exhausted, auth_range and the rest — so a program can tell them apart without parsing error_message; it is None on every other result. observed_value is whatever the confirming re-read returned, in the type the channel holds — a number, a string, an enum label, a waveform; observed_number narrows it to a float where that makes sense.

Alarm state (alarm_status, alarm_severity) is carried protocol-agnostically — the alarm name as a string, the severity as an int — and is information reported with the write, never a reason to raise. None means “not reported”, which stays distinct from a reported healthy value (alarm_severity=0). Mapping a protocol’s raw codes to those names is the connector’s job, so this shared module imports no control-system constants.

channel_address: str#
value_written: Any#
outcome: WriteOutcome#
refusal_reason: RefusalReason | None = None#
error_message: str | None = None#
observed_value: Any = None#
alarm_status: str | None = None#
alarm_severity: int | None = None#
notes: str | None = None#
verdict_reason: str | None = None#
__post_init__()[source]#

Coerce outcome and refusal_reason to members, then check the shape.

A StrEnum crosses the connector-host IPC as the plain string JSON encodes it to, and the codec rebuilds the dataclass by calling it with the decoded fields — so what arrives here on the parent side is a str. Coercing once, on construction, is what lets every consumer compare against the members whichever side of the process boundary it runs on.

Raises:

ValueError – refusal_reason is not a known reason, is missing on a refused result or set on any other, or error_message is missing on a refused, failed or unconfirmed result or set on any other.

property observed_number: float | None#

observed_value as a float, or None when it is not a number.

__init__(channel_address, value_written, outcome, refusal_reason=None, error_message=None, observed_value=None, alarm_status=None, alarm_severity=None, notes=None, verdict_reason=None)#
class osprey_connectors.control_system.ControlSystemConnector[source]#

Bases: ABC

Abstract base class for control system connectors.

Implementations provide interfaces to different control systems (EPICS, LabVIEW, Tango, the simulator, etc.) using a unified API.

Example

>>> connector = await ConnectorFactory.create_control_system_connector()
>>> try:
>>>     channel_value = await connector.read_channel('BEAM:CURRENT')
>>>     print(f"Beam current: {channel_value.value} {channel_value.metadata.units}")
>>> finally:
>>>     await connector.disconnect()
property transport: str | None#

The factory-stamped wire this instance speaks (None off the factory).

current_value_reader()[source]#

This connector’s own way to read a channel’s present value.

Handed to LimitsValidator.validate() so the max_step check measures the step over the client and the target the write itself is bound for. The validator is shared by every connector and owns no client; a connector that cannot read synchronously answers None here, and a max_step channel on it fails closed rather than being measured over somebody else’s protocol.

Return type:

CurrentValueReader | None

classmethod __init_subclass__(**kwargs)[source]#

Auto-wrap write methods with the write-verdict pre-check.

Any subclass that defines write_channel() or write_multiple_channels() gets them transparently wrapped. The wrapper checks _writes_enabled before calling the original method. When the verdict refuses, returns REFUSED results worded by _verdict_refusal() — no exception is raised.

This fires before limits validation (intentional: fast-reject when writes are disabled, avoiding unnecessary validation work).

Past that check the wrapper asks session_hold_refusal(), kept out of _writes_enabled because that property also chooses the gateway: a held session’s write is refused here while its connection stays as it is.

A process that names a program’s write authorization (named_authorization()) is judged instead by authorized_execution_verdict() on the call’s channels and values, which spends the call’s one step before anything is put (_authorized_refusal()). A batch is the base class’s write_multiple_channels() under an authorization, a subclass’s own batch included: judged whole and spent once, then each operation written past the guard. A process naming none is judged exactly as before.

Past both checks the original method runs inside open_door(), so the raw-client guard attributes its put to a connector. A connector whose writes are disabled never opens the door.

A subscribe() written before on_connection existed is wrapped too (_compat_subscribe_without_on_connection(), deprecated), so every connector takes the keyword and a facility’s own connector keeps working.

abstractmethod async connect(config)[source]#

Establish connection to control system.

Parameters:

config (dict[str, Any]) – Control system-specific configuration

Raises:

ConnectorUnavailableError – If connection cannot be established

abstractmethod async disconnect()[source]#

Close connection to control system and cleanup resources.

abstractmethod async read_channel(channel_address, timeout=None)[source]#

Read current value of a channel.

Parameters:
  • channel_address (str) – Address/name of the channel

  • timeout (float | None) – Optional timeout in seconds

Returns:

ChannelValue with current value, timestamp, and metadata

Raises:
  • ChannelUnreachableError – This channel cannot be reached or did not answer in time; the connector stays in place

  • ConnectorUnavailableError – The connector’s own transport is gone

  • TimeoutError – If operation times out

  • ValueError – If channel address is invalid

  • ChannelNotFoundError – The address is not a channel of the facility (a connector that holds the facility’s address set)

Return type:

ChannelValue

abstractmethod async write_channel(channel_address, value, timeout=None, confirm=None)[source]#

Write a value to a channel, confirming it unless asked not to.

Parameters:
  • channel_address (str) – Address/name of the channel

  • value (Any) – Value to write

  • timeout (float | None) – Optional timeout in seconds

  • confirm (bool | None) – Whether to re-read the channel and compare, or None to let the connector resolve the policy for this channel

Returns:

ChannelWriteResult carrying the outcome and what the channel was seen to hold

Raises:
  • ChannelUnreachableError – This channel cannot be reached or did not answer in time; the connector stays in place

  • ConnectorUnavailableError – The connector’s own transport is gone

  • TimeoutError – If operation times out

  • ValueError – If value is invalid for this channel

  • PermissionError – If write access is not allowed

Return type:

ChannelWriteResult

Outcomes:

The connector sets exactly one WriteOutcome on the result, and no consumer re-derives a verdict of its own:

  • refused — nothing was written; refusal_reason says why.

  • failed — the value was sent and the control system did not take it.

  • confirmed — a fresh re-read holds the value sent, in any alarm state. Alarm state is reported with the write, never raised on.

  • mismatch — the re-read holds a different value. A clamped or rounded setpoint is reported here, not tolerated.

  • unconfirmed — the value was sent, but not acknowledged in time or the re-read itself failed, so what the channel holds is unknown.

  • unrequested — confirm=False: nothing was checked.

The comparison is values_match(), one rule shared by every connector; there is no configurable tolerance anywhere.

Omission sentinel:

confirm=None means “no opinion” — it is NOT False. A caller with no opinion leaves the keyword off entirely; the connector then resolves the policy for this specific channel through _resolve_confirm(): the channel’s own confirm entry in the limits database, else True. The limits database is the single home of write policy.

An explicit confirm=False is an answer and must travel as one, so every guard on the omission is if confirm is not None and never if confirm: — the truth test would silently turn a declined confirmation back into “resolve it” and confirm anyway.

Two-layer safety model:

Per-write mechanical safety lives INSIDE the connector and is applied per individual channel write: the writes_enabled gate, limits validation (min/max/step/writable), and the fail-closed validation path. This is complete mediation at the write primitive — every write passes through it.

Per-intent human authorization is a SEPARATE layer at the tool boundary: the PreToolUse approval hook (and, for scans, the promote token) gate the intent to write, once per intent — not once per channel write.

The two are orthogonal and complementary: the connector cannot be talked out of a mechanical refusal, and the approval layer cannot substitute for that refusal.

async write_channel_checked(channel_address, value, **kwargs)[source]#

Await write_channel and enforce the reference monitor’s denial contract.

refused (policy/limits/validation) -> raises ChannelWriteBlockedError. failed / mismatch / unconfirmed -> raises ChannelWriteFailedError. Connection failures and timeouts propagate unchanged. confirmed or unrequested -> returns the ChannelWriteResult.

A scan device setter wraps this so any raise aborts the RunEngine, while a confirmed write returns and the scan proceeds; osprey.runtime.write_channel routes through it for the same reason. Extra keyword arguments (confirm, timeout) pass straight through to write_channel. The result inspection itself lives in raise_for_write_result(), which the multi-channel paths share.

Return type:

ChannelWriteResult

abstractmethod async read_multiple_channels(channel_addresses, timeout=None)[source]#

Read multiple channels efficiently (can be optimized per control system).

Parameters:
  • channel_addresses (list[str]) – List of channel addresses to read

  • timeout (float | None) – Optional timeout in seconds

Returns:

Dictionary mapping channel address to ChannelValue (May exclude channels that failed to read)

Return type:

dict[str, ChannelValue]

async write_multiple_channels(operations, timeout=None, confirm=None)[source]#

Write several channels as one batch: every write checked, then every write sent.

What a batch means, on every connector:

  1. The checks are all-or-nothing. Every write passes every check a single write_channel() makes before it sends: the write verdict, the connector’s own refusals and the limits, max_step included. The channels a step is measured on are read together, once, before anything is sent. If one write is refused there, no write of the batch is sent, and every channel gets a refused result: a refused write its own reason, each other write BATCH_REFUSED naming a refused one.

  2. Past the checks every write is sent and verified on its own. One result per channel, with the outcome a single write would report. A write that fails, mismatches or stays unconfirmed does not recall the others, which may already hold their values. The batch has failed unless every result may be proceeded on (raise_for_write_result()).

The promise covers what is known before the send. A refusal the control system gives only at the send (a connector with no _write_precheck(), a value the target coerces or a read-only channel it rejects) can come after earlier writes of the batch went out; each result still says what happened to its own channel.

A batch names a channel once. One that names a channel more than once is refused whole: a later write to it could only be checked against an earlier one that may never land.

The write verdict is asked again right before the send, so a switch turned off, a hold or a stop that arrives while the batch is checked refuses every write not yet sent.

A batch never raises ChannelLimitsViolationError: a limits refusal is a refused result with reason LIMITS. A channel whose send raised ChannelUnreachableError or timed out is unconfirmed. An error of the connector itself (ConnectorUnavailableError) is raised, and the batch’s outcome is then unknown.

This method is the batch on every connector. A connector changes how a batch is checked or sent through _write_precheck(), _current_values() and _send_batch(), not by overriding it. A refusal a connector makes only inside its own write_channel() is not known before the send: it belongs in _write_precheck().

Parameters:
  • operations (list[tuple[str, Any]]) – List of (channel_address, value) tuples

  • timeout (float | None) – Optional timeout in seconds, given to each write

  • confirm (bool | None) – Whether every channel in the batch is confirmed, or None to let each channel resolve its own policy

Returns:

List of ChannelWriteResult in the same order as operations

Return type:

list[ChannelWriteResult]

Note

An omitted confirm is not resolved here: each channel resolves its own policy from the limits database, as write_channel() documents. An explicit confirm, False as much as True, reaches every channel unchanged.

In a process that names a program’s write authorization the whole call is judged and its one step spent before anything is checked or sent; a batch the limits then refuse has still spent it.

abstractmethod async subscribe(channel_address, callback, *, on_connection=None)[source]#

Subscribe to channel changes.

Parameters:
  • channel_address (str) – Address/name of the channel

  • callback (Callable[[ChannelValue], None]) – Function called when value changes (receives ChannelValue)

  • on_connection (Callable[[bool], None] | None) – Optional function told the channel’s connection state: True when it connects (before the first value of that connection), False when it drops. A channel that never connects reports nothing. Called on the event loop, like callback. Connectors whose control system reports no connection state (DOOCS, Tango) accept and ignore it. A subclass whose subscribe does not take it is told True before its first value by the base class instead.

Returns:

Subscription ID for later unsubscribe

Return type:

str

abstractmethod async unsubscribe(subscription_id)[source]#

Cancel subscription to channel changes.

Parameters:

subscription_id (str) – Subscription ID returned by subscribe()

async wait_stale()[source]#

Raise ConnectorUnavailableError once this connector’s transport has gone stale.

Stale means the control system serves a channel again while this process’s client library still holds it down and will not notice on its own; only a new connector in a new process cures it. That is a lost connector, so it is raised as the lost-connector root, and the supervisor that owns the connector’s lifetime replaces it as it would after any ConnectorUnavailableError (osprey_connectors.recovery). It never returns normally. A connector that can tell (EPICS with a name server) overrides this method.

This default serves every connector where staleness cannot occur or cannot be told (DOOCS, Tango, …): it waits for ever. A caller that is shutting down cancels it.

An overriding connector counts only channels that connected in this process, so in the successor of a stale process a channel that never comes back cannot drive a respawn loop.

channel_key(address)[source]#

The one name every spelling of a channel’s address shares on this control system.

A caller that must treat two addresses as one channel (a session admitting one write per channel at a time) compares these keys; the read or write itself still goes to the address as given. Pure and synchronous. This default strips surrounding whitespace; a connector whose protocol spells one channel several ways (EPICS: ca://X, X.VAL and X) overrides it.

Return type:

str

abstractmethod async get_metadata(channel_address)[source]#

Get metadata about a channel.

Parameters:

channel_address (str) – Address/name of the channel

Returns:

ChannelMetadata with units, alarm status, description, and (where the control system reports one) a display range

Raises:
Return type:

ChannelMetadata

abstractmethod async validate_channel(channel_address)[source]#

Check if channel exists and is accessible.

Parameters:

channel_address (str) – Address/name of the channel

Returns:

True if channel is valid and accessible

Return type:

bool

class osprey_connectors.control_system.LimitsValidator(limits_database, policy_config, raw_db=None, failsafe_reason=None)[source]#

Bases: object

Core limits validation engine.

Performs synchronous validation - no async I/O to keep it simple. Raises exceptions directly instead of returning result objects.

__init__(limits_database, policy_config, raw_db=None, failsafe_reason=None)[source]#
static resolve_database_path(db_path, project_root, config_path=None)[source]#

Resolve a relative database_path the same way for every caller.

A relative database_path is written alongside the config it appears in, so the anchor is the directory of the config that is actually in use: config_path, when the caller can name the file it loaded (see osprey_connectors.config.default_config_path()). This is what makes the resolution independent of how the process was launched — a Claude Code hook, an MCP server, and a host verb anchored via config_anchored_at all load the render’s config and find the data/ tree the build copied next to it.

Fallbacks, for callers that cannot name the loaded config: Path(CONFIG_FILE).parent when that variable is set (a container deploy names the config mounted inside the container while project_root may record a host path the container does not have), else the config’s own project_root key. Note that under the four-zone repo layout the render lives at <repo>/build/config.yml while project_root names <repo> — the project_root branch is a last resort, not an equivalent spelling.

Returns db_path unchanged if it is already absolute, or if no base is available.

Return type:

str

classmethod configured_database_path(*, config_lookup=None, config_path=None)[source]#

The file LIMITS_DATABASE_CONFIG_KEY names, resolved; or None.

The one reading of that key. Every caller that used to walk the config segments and call resolve_database_path() itself asks here, so the build, the bridge, the roster and the knowledge graph cannot resolve the same relative path to different files.

None covers every way of naming nothing: key absent, not a string, blank. Existence is not probed – a configured file that is not there is the loader’s finding, with the loader’s message.

Parameters:
Returns:

The resolved path as a string, or None.

Return type:

str | None

classmethod load_configured_database(*, config_lookup=None, config_path=None)[source]#

Resolve and load the deployment-wide limits database.

The database path is deployment-wide even where the posture is not: a deployment mounts one limits file (compose_generator.py binds a single path), so a per-type block changes policy and never the data. This is the half of validator construction that is the same for every posture, and the same read the build’s pre-deploy parse and the bridge’s startup gate make – kept in one place so that none of them can drift in how they resolve a relative path or in which load failures they report.

Failure is reported rather than raised because every caller answers it its own way: the connector with a fail-safe validator that blocks every write, the build with a refusal line, the bridge with a startup refusal. Returning None alone would leave a connector’s writes unchecked, and raising would crash one on a deployment that never writes at all.

Parameters:
Returns:

either the (limits_database, raw_database) tuple, or a sentence naming what could not be read, complete enough to be quoted by any caller.

Return type:

A (loaded, reason) pair with exactly one half set

static writable_addresses(db_path)[source]#

The addresses a limits database declares writable.

Read through _load_limits_database() rather than from the raw JSON, so the metadata keys and the per-entry validation are applied by the same code the write path applies them with: writable is read from each entry, an entry that does not state it fails the load, and a top-level defaults key fails the load.

Parameters:

db_path (str | Path) – Path to a channel_limits.json-shaped file.

Returns:

The writable addresses.

Raises:

ValueError – If the file is missing, is not JSON, is not a JSON object, or carries an entry the validator refuses.

Return type:

frozenset[str]

classmethod from_config(*, connector_type=None, target=None)[source]#

Load a validator for the limits posture the caller acts under.

Three call shapes, one per identity a caller can hold:

  • Neither argument asks the deployment-wide question, control_system.limits_checking, and never resolves a target. It is what a caller holding no machine of its own asks — the connector registry’s log line, the executor’s config helper — and it is the shape every caller had before per-type blocks existed, so a deployment that wrote none behaves as it did — except that a deployment-wide leaf written as something other than a literal boolean now blocks every write instead of being read as truthy.

  • connector_type is what a connector, factory or IPC child asks: they know which connector type they are and never which target selected it.

  • target is what a tool, hook, roster or the executor asks: they follow the deployment’s control target, which is resolved to its connector type here so both shapes read one posture.

A present control_system.connector.<type>.limits_checking block overrides the deployment-wide pair whole; absent, the deployment-wide block answers. The key that answered travels into policy so a later refusal names the config line an operator can edit.

Parameters:
  • connector_type (str | None) – The connector type to resolve the posture for, as the config’s control_system.connector table keys it.

  • target (str | None) – The session control target to resolve the posture for, one of osprey_connectors.types.CONTROL_TARGETS. A target that does not resolve to a type gets the deployment-wide block, as the write posture does.

Returns:

An enforcing validator; a fail-safe validator that blocks every write when the resolved block is incomplete or the limits database is unavailable; or None when limits checking is off for this posture or the config could not be read at all.

Raises:

TypeError – If both connector_type and target are given. A target already names a type, so stating both states the posture twice and leaves it undefined which one the caller meant. Raised before any config is read, so it surfaces as the caller bug it is rather than as a missing-config None.

Return type:

LimitsValidator | None

classmethod from_config_most_restrictive()[source]#

Load a validator for the posture that holds across every reachable target.

What a caller with no target of its own has to assume. The stdlib limits hook is the one that needs it: when the deployment’s control target cannot be read — none written yet, an unreadable state directory, a target that resolves to nothing — it still has to decide about a write, and the machine it is deciding about is any of the ones a session here can select.

The fold is osprey_connectors.types.most_restrictive_limits_posture()’s: limits checking is on when any reachable target has it on, and the mode is optional only where every reachable target is optional. The result names the deployment-wide keys, because no per-type line decides a union and naming one would send an operator to edit a single machine rather than the answer.

Returns:

An enforcing validator, a fail-safe one, or None — the same envelope from_config() returns, for the same reasons.

Return type:

LimitsValidator | None

resolve_confirm(channel_address)[source]#

Whether a write to this channel must be confirmed by re-reading it.

Resolution: the channel’s own confirm, else True. Read off the raw database, which is where confirm lives: it is write policy, not a limit, so it never enters ChannelLimitsConfig.

Parameters:

channel_address (str) – Channel address being written

Returns:

True when the write must be confirmed (the fleet default).

Return type:

bool

measures_step(channel_address)[source]#

Whether validate() reads this channel’s present value.

True for a channel with a max_step. A caller that validates many writes at once reads exactly these channels beforehand, together.

Return type:

bool

validate(channel_address, value, *, read_current=None)[source]#

Validate a channel write operation (synchronous, optional I/O for max_step).

Raises ChannelLimitsViolationError if validation fails. Returns None if validation passes.

Note: If max_step is configured for the channel, this performs one synchronous read to get the current value. This adds ~50-100ms latency but provides important step-size safety checking. This validator owns no control-system client of its own – it is shared by every connector – so the caller that is about to write supplies the read.

Parameters:
  • channel_address (str) – Channel address to validate

  • value (object) – Value to write

  • read_current (Callable[[str], object] | None) – The caller’s own way to read channel_address’s present value, used only when the channel configures max_step. Omitting it on such a channel fails the write closed: a step that cannot be measured cannot be approved.

Raises:

ChannelLimitsViolationError – If any validation check fails

validate_without_step_check(channel_address, value)[source]#

Every limits check that can be made without reading the machine.

For a caller that is not the one performing the write, and so has no client to measure a step over: the PreToolUse limits hook, which gates the write request before it reaches a connector at all. It applies the database, the writable flag and the min/max bounds, and leaves max_step to the writer – which owns the client the write goes through and checks it moments later in validate(). Refusing here for want of a reader would take max_step off the mediated write path entirely rather than enforcing it.

Parameters:
  • channel_address (str) – Channel address to validate

  • value (object) – Value to write

Raises:

ChannelLimitsViolationError – If any of those checks fails

class osprey_connectors.control_system.WriteOutcome(value)[source]#

Bases: StrEnum

What became of one channel write — the single owned verdict.

The connector that performed the write is the only producer of this value; every consumer (MCP tool, osprey.runtime, the Bluesky bridge, the connector-host IPC) reads it and none re-derives a verdict of its own.

  • REFUSED — nothing was written; refusal_reason says why.

  • FAILED — the value was sent and the control system did not take it.

  • CONFIRMED — a re-read of the channel holds the value sent, in any alarm state. Alarm state is reported, never raised on.

  • MISMATCH — the re-read holds a different value (a clamped or rounded setpoint is reported here, not tolerated).

  • UNCONFIRMED — the value was sent, but not acknowledged in time or the re-read itself failed, so what the channel holds is unknown.

  • UNREQUESTED — confirm=False: nothing was checked.

REFUSED = 'refused'#
FAILED = 'failed'#
CONFIRMED = 'confirmed'#
MISMATCH = 'mismatch'#
UNCONFIRMED = 'unconfirmed'#
UNREQUESTED = 'unrequested'#
osprey_connectors.control_system.mapping_config_lookup(config)[source]#

A get_config_value-shaped lookup over an already-loaded config.

For the callers that hold the config as a dict rather than through the live configurable – the build reading a render’s config.yml, the roster reading the project config it was handed – so they resolve the limits database through the same path as the runtime instead of walking the segments themselves.

Parameters:

config (Mapping[str, object]) – The loaded configuration mapping.

Returns:

A callable (dotted_key, default) -> value that walks nested mappings and answers default for any segment that is not there.

Return type:

Callable[[str, object], object]

osprey_connectors.control_system.mark_long_lived_session()[source]#

Record that this process holds a long-lived control session.

Called by osprey.runtime.session.ControlSession.open(). From then on a readonly refusal in this process uses the deployment-wide wording: the process was started by the deployment, not submitted as one readonly script, so “resubmit it with execution_mode=’readwrite’” would send the operator to a script that does not exist. Irreversible for the process.

osprey_connectors.control_system.raise_for_write_result(result)[source]#

Enforce the reference monitor’s denial contract on one write result.

The single place that decides whether a ChannelWriteResult counts as a write the caller may proceed on. Every caller that must not proceed on an unconfirmed write routes through here, so the refusal/failure distinction cannot drift between the single-channel and multi-channel paths.

The verdict is read off ChannelWriteResult.outcome and nothing else. The connector that performed the write already decided; re-deriving a verdict here from a second field is what let a write to an unreadable channel report itself as a success.

Parameters:

result (ChannelWriteResult) – The result returned by a connector’s write_channel.

Returns:

The result unchanged, when the outcome is confirmed — whatever the alarm severity, since alarm state is reported and never raised on — or unrequested, where no confirmation was asked for.

Raises:
  • ChannelWriteBlockedError – The outcome is refused: no value was written. refusal_reason names why; ChannelWriteBlockedError.refuser() says who refused.

  • ChannelWriteFailedError – The value was sent and the write did not come back confirmed — failed, mismatch or unconfirmed, each raising under its own word. The exception carries the outcome, the value sent and the value observed, so a mismatch message names both numbers.

Return type:

ChannelWriteResult

osprey_connectors.control_system.raise_for_write_results(results)[source]#

Enforce the denial contract on a batch’s results.

raise_for_write_result() for each result in batch order, the writes their batch only held back (BATCH_REFUSED) last: a batch stopped at its checks raises for the write that was refused, wherever it stands.

Returns:

The results unchanged, when every one may be proceeded on.

Return type:

Sequence[ChannelWriteResult]

osprey_connectors.control_system.step_read_timeout_seconds(config, connector_type=None)[source]#

The max_step fresh-read budget one connector block declares.

Parameters:
  • config (Mapping[str, object] | None) – A connector’s own config section — the mapping control_system.connector.<type> resolves to.

  • connector_type (str | None) – The type that block belongs to, so a warning names the key an operator has to go and fix. None leaves the type a placeholder in that message.

Returns:

The declared budget, or DEFAULT_STEP_READ_TIMEOUT_SECONDS when the block declares none or declares something that is not a positive number. A value that cannot be used is warned about, naming the key and what was found, and then falls back rather than raising: this resolves on the write path, and a typo in a tuning key must not be the thing that takes writes down.

Return type:

float

osprey_connectors.control_system.values_match(sent, observed, *, enum_label=None)[source]#

True when observed is the value sent — the one comparison rule.

Applied in order, and symmetric: swapping the arguments cannot change the answer.

  1. A string against a reported enum_label compares as text: an enum channel written as "Open" reads back as its integer index, and the label the connector resolved for that reading is what the text is compared with. A connector that reports no enum_label (DOOCS) falls through to the ordinary comparison.

  2. A length-1 sequence is unwrapped to its element, on both sides.

  3. After unwrapping, exactly one side a sequence is False: a scalar is not a vector. This is what stops a numpy broadcast (np.array([5.0, 5.0]) == 5.0 reduced by .all()) from manufacturing a match.

  4. Two sequences of unequal length are False; equal lengths compare elementwise.

  5. Two real numbers (bools excluded) compare by math.isclose with rel_tol=1e-6 — roughly eight float32 epsilons, so a legitimate float32 store still matches — and abs_tol=0.0, so nothing is close to zero but zero. There is no configurable tolerance anywhere.

  6. Anything else compares by ==.

  7. Any exception means the two cannot be compared, which is not a match.

Return type:

bool

The write door: marks a put as made by a connector, not by a raw client.

A connector opens the door around its own call into a control-system client library; the raw-client guard asks door_is_open() and lets a put through only when the answer is yes. A put made from user code that reached for the client directly finds the door closed.

Contract. A connector makes its client put in the context that opened the door, inside asyncio.to_thread started from that context, or in a coroutine handed to another loop with asyncio.run_coroutine_threadsafe from that context. The flag is a context variable, so it reaches exactly the code that shares that context: asyncio.to_thread and run_coroutine_threadsafe both run the work in a copy of it and carry the open door with it, as does every task created while the door is open. loop.run_in_executor, a raw executor submit and a bare threading.Thread start from a fresh context and see the door closed, so a connector that puts behind one of those hops is refused.

Cooperative bypasses. The door records attribution, not permission, and some paths open it for code that is not a connector’s own put. These are accepted, because attribution is not a boundary:

  • Anything a connector’s put coroutine starts on the CA loop while it runs (ca_loop) inherits the door with it. libca’s own callback threads start from a fresh context and never carry it.

  • ControlSystemConnector wraps every subclass’s write_channel and write_multiple_channels, including those of a user-defined connector subclass, so a user-defined connector puts inside an open door.

This module is stdlib-only: the guard that reads it runs in executor sandboxes and notebook kernels where osprey is not importable.

osprey_connectors.control_system.write_door.door_is_open()[source]#

Whether the calling context is inside open_door().

Return type:

bool

osprey_connectors.control_system.write_door.open_door()[source]#

Open the write door for the body of the with block.

Return type:

Iterator[None]

The archiver connector contract.

ArchiverConnector, its metadata model and store extent, the processing modes, the field name a channel is stored under, and the client arguments for the MongoDB archive store, which the archive recorder and the deploy-time seed open without the connector. The concrete archivers are the _*_archiver_connector modules beside this one.

class osprey_connectors.archiver.ArchiveExtent(channels=None, oldest=None, newest=None, reason=None)[source]#

Bases: object

What an archive store holds, as far as the archiver can say.

Every field is None when unknown. channels is the set of channel addresses the store records now; oldest and newest are the instants of its oldest and newest samples; reason says why a part is unknown.

channels: frozenset[str] | None = None#
oldest: datetime | None = None#
newest: datetime | None = None#
reason: str | None = None#
__init__(channels=None, oldest=None, newest=None, reason=None)#
class osprey_connectors.archiver.ArchiverConnector[source]#

Bases: ABC

Abstract base class for archiver connectors.

Implementations provide interfaces to different archiver systems using a unified API that returns pandas DataFrames.

Example

>>> connector = await ConnectorFactory.create_archiver_connector()
>>> try:
>>>     df = await connector.get_data(
>>>         channels=['BEAM:CURRENT', 'BEAM:LIFETIME'],
>>>         start_date=datetime(2024, 1, 1),
>>>         end_date=datetime(2024, 1, 2)
>>>     )
>>>     print(df.head())
>>> finally:
>>>     await connector.disconnect()
abstractmethod async connect(config)[source]#

Establish connection to archiver.

Parameters:

config (dict[str, Any]) – Archiver-specific configuration

Raises:

ConnectorUnavailableError – If connection cannot be established

abstractmethod async disconnect()[source]#

Close connection to archiver and cleanup resources.

abstractmethod async get_data(channels, start_date, end_date, precision_ms=1000, timeout=None, processing='raw')[source]#

Retrieve historical data for one or more channels.

Parameters:
  • channels (list[str]) – List of channel addresses to retrieve. Addresses are protocol-agnostic: EPICS PV names, DOOCS property addresses, or whatever the configured backend keys its store by.

  • start_date (datetime) – Start of time range

  • end_date (datetime) – End of time range

  • precision_ms (int) – Bin width in milliseconds; <= 0 means full resolution. A backend that cannot express the requested width must raise ValueError rather than serve a different one. Bins are anchored on start_date: the same window and width cut the same lattice for every channel in the request and for every processing mode. A backend that bins on a grid of its own is the documented exception — the EPICS Archiver Appliance’s operators are epoch-anchored, and the window merely clips them.

  • timeout (int | None) – Optional timeout in seconds

  • processing (str) – Aggregation applied within each precision_ms bin. One of “raw”, “mean”, “min”, “max”, “median”, “std”, “count”. Anything else raises ValueError.

Return type:

DataFrame

Waveform channels:

A waveform channel’s sample is one whole trace: its value is a list[float] with one entry per element of the channel’s shape. Only "raw" processing is defined for waveforms, and it returns every stored trace in the window at its own timestamp, unbinned, whatever precision_ms is — dropping or averaging traces would describe pulses nothing ever captured. Any other mode on a waveform channel raises ValueError naming the channel. A backend that cannot read waveforms at all says so with its own error rather than returning something else in their place.

Returns:

A long-format DataFrame with columns timestamp (datetime64[ns, UTC]), channel (str), and value (float64 unless a channel is non-numeric or a waveform), sorted by channel then timestamp. Each channel contributes only its own real samples or per-bin aggregates — no forward-fill, no shared grid, no bin for a period with no samples. A channel with no data in range contributes no rows; an empty result is an empty frame with these columns.

Raises:
  • ConnectorUnavailableError – If archiver cannot be reached

  • TimeoutError – If operation times out

  • ValueError – If time range, channel addresses, or processing mode are invalid, or if a non-“raw” processing mode is requested for a channel whose values are non-numeric or that is a waveform channel

Return type:

DataFrame

abstractmethod async get_metadata(channel)[source]#

Get archiving metadata for a channel.

Parameters:

channel (str) – Channel address

Returns:

ArchiverMetadata with archiving information

Raises:
Return type:

ArchiverMetadata

abstractmethod async check_availability(channels)[source]#

Check which channels are archived.

Parameters:

channels (list[str]) – List of channel addresses to check

Returns:

Dictionary mapping channel address to availability status; None where this archiver cannot say.

Raises:

RuntimeError – If the archiver is not connected; a disconnected archiver has no store to ask, so it answers nothing.

Return type:

dict[str, bool | None]

async store_extent()[source]#

What the store holds: its channels, oldest and newest sample.

Optional. The default answers every part unknown, with a reason, so an archiver that cannot list its store keeps working unchanged.

Return type:

ArchiveExtent

class osprey_connectors.archiver.ArchiverMetadata(channel, is_archived, archival_start=None, archival_end=None, sampling_period=None, description=None)[source]#

Bases: object

Archiving metadata for one channel.

channel is the same protocol-agnostic channel address the control-system connectors take, and the same value that appears in the channel column of ArchiverConnector.get_data().

is_archived is None when this archiver cannot say whether it archives the channel; description then says why.

channel: str#
is_archived: bool | None#
archival_start: datetime | None = None#
archival_end: datetime | None = None#
sampling_period: float | None = None#
description: str | None = None#
__init__(channel, is_archived, archival_start=None, archival_end=None, sampling_period=None, description=None)#
osprey_connectors.archiver.address_overrides()[source]#

The in-network store address this process was given, if it was given one.

Returns:

(host, port), either of which is None when the corresponding variable is unset — or set to whitespace, which is treated as unset rather than as an address of nothing. A caller applies whichever half it got over its own configured value, and keeps its own rules about what to do when neither source supplies one.

Raises:

ValueError – If the port override is set to something that is not an integer. Silently falling back to the configured host-side port would send a container to an address nothing serves, and the reason would be a typo nobody is looking at.

Return type:

tuple[str | None, int | None]

osprey_connectors.archiver.field_name(address)[source]#

The field name the archive stores address under.

Parameters:

address (str) – A channel address.

Returns:

address with %, . and NUL escaped as %25, %2E and %00, a leading $ as %24, and the first character of an address equal to one of the archive’s own document fields; address itself when none of these applies.

Raises:

ValueError – for the empty address, which has no field name.

Return type:

str

osprey_connectors.archiver.mongo_client_kwargs(*, url, host, port, username, password, auth_source, ca_bundle, timeout_s)[source]#

The keyword arguments for pymongo.MongoClient.

Every MongoDB client OSPREY opens takes its arguments from here: the agent’s connector, the archive recorder and the archive rewrite. One block can therefore never produce two different clients. This is the only place pymongo’s keyword names are spelled.

Pure: it reads no environment and does no I/O. A caller applies the address overrides (address_overrides()) to host and port itself, before calling, because a host-side caller must take nothing from the ambient environment.

A key whose value is unset is left out rather than passed as None.

Parameters:
  • url (str | None) – A connection string; when set it is passed as host and no port is passed.

  • host (str | None) – The store’s host, used when url is unset.

  • port (int | None) – The store’s port, used when url is unset.

  • username (str | None) – The login user; password and auth_source go with it. Without one, neither is passed.

  • password (str | None) – The login secret.

  • auth_source (str | None) – The database the user is defined in.

  • ca_bundle (str | None) – A CA file to trust; setting it turns TLS on.

  • timeout_s (float) – Seconds to wait for a server.

Return type:

dict[str, Any]