Source code for osprey_connectors.control_system._limits_validator

"""Runtime channel limits validation engine - simplified single-layer design."""

import json
import math
import numbers
import os
import re
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from pathlib import Path
from typing import TypeGuard

from osprey_connectors.logger import get_logger
from osprey_connectors.types import (
    LIMITS_MODE_OPTIONAL,
    LimitsPosture,
    limits_database_required,
    most_restrictive_limits_posture,
    target_limits_posture,
    type_limits_posture,
)

logger = get_logger("limits_validator")


# Reserved metadata fields (underscore prefix)
# These are for documentation only and don't affect validation
METADATA_FIELDS = {"_comment", "_version", "_last_updated", "_description"}

#: The one config key naming the channel-limits database. One value, one file,
#: everywhere it is spoken about: the connector's own lookup, the compose bind
#: mount, the build's parse, the bridge's startup gate, the roster's direction
#: source, the knowledge graph's direction assignment, and every refusal that
#: names the key back to the operator. Spelled here and imported everywhere
#: else, because a key spelled six times is a key that drifts.
LIMITS_DATABASE_CONFIG_KEY = "control_system.limits_checking.database_path"

#: The config key the last-resort path anchor is read from.
_PROJECT_ROOT_CONFIG_KEY = "project_root"

#: The signature every ``config_lookup`` here has: that of
#: :func:`osprey_connectors.config.get_config_value`.
ConfigLookup = Callable[[str, object], object]

#: The signature of the fresh-read primitive :meth:`LimitsValidator.validate`
#: takes for the ``max_step`` check: one channel address in, that channel's
#: present value out. Every control system can read a channel; none of them
#: agree on how, so the caller that is about to write supplies its own.
CurrentValueReader = Callable[[str], object]

#: Ceiling on the fresh read a ``max_step`` check makes, in seconds, when the
#: deployment names none. The check sits in front of a write an operator is
#: waiting on, so a channel that does not answer must fail closed quickly
#: rather than hold the write open: running out of budget answers ``None``,
#: which refuses the write.
#:
#: How long that read takes is a property of the facility's control network,
#: exactly like the connector's own ``timeout_s`` — a gateway two hops away
#: answers slower than a soft IOC on the same host — so a deployment overrides
#: it with ``control_system.connector.<type>.step_read_timeout_s``.
DEFAULT_STEP_READ_TIMEOUT_SECONDS = 2.0

#: The per-connector key that overrides it, spelled once so the connector and
#: the python-executor sandbox cannot read two different names.
STEP_READ_TIMEOUT_KEY = "step_read_timeout_s"

#: The ``violation_type`` of a write refused because its value is not a finite
#: real number while the channel has a numeric limit to hold it to.
INVALID_NUMERIC_VALUE = "INVALID_NUMERIC_VALUE"


#: C's ``isspace`` set: what EPICS's C conversion skips around a numeral.
_C_WHITESPACE = " \t\n\v\f\r"

#: The numerals EPICS's C conversion parses into an integer field: ``strtol`` with base 0,
#: so ``0x`` is hex and a leading ``0`` is octal.
_C_INTEGER = re.compile(r"[+-]?(?:0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)")

#: The decimal numerals EPICS's C conversion parses into a floating-point field (``strtod``).
_C_DECIMAL_FLOAT = re.compile(r"[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")

#: The hexadecimal numerals ``strtod`` also takes: ``0x10``, ``0x1.8p3``.
_C_HEX_FLOAT = re.compile(
    r"[+-]?0[xX](?:[0-9a-fA-F]+\.?[0-9a-fA-F]*|\.[0-9a-fA-F]+)(?:[pP][+-]?[0-9]+)?"
)


def _c_integer(text: str) -> int | None:
    """``text`` as C reads it into an integer field, or ``None`` if it errors there."""
    if not _C_INTEGER.fullmatch(text):
        return None
    sign = -1 if text[0] == "-" else 1
    digits = text.lstrip("+-")
    if digits[:2] in ("0x", "0X"):
        return sign * int(digits, 0)
    if len(digits) > 1 and digits[0] == "0":
        return sign * int(digits, 8)
    return sign * int(digits)


def _c_float(text: str) -> float | None:
    """``text`` as C reads it into a floating-point field, or ``None`` if it errors there."""
    try:
        if _C_DECIMAL_FLOAT.fullmatch(text):
            return float(text)
        if _C_HEX_FLOAT.fullmatch(text):
            return float.fromhex(text)
    except OverflowError:
        return None
    return None


def c_numeral(text: str, *, integer_field: bool) -> int | float | None:
    """``text`` as the IOC's C conversion reads it into one field type, or ``None``.

    An integer field reads ``strtol`` numerals only; a floating-point field
    reads ``strtod``'s. Surrounding C whitespace is skipped, as C skips it.
    """
    text = text.strip(_C_WHITESPACE)
    return _c_integer(text) if integer_field else _c_float(text)


def _numeral_or_reason(value: str) -> tuple[float | None, str | None]:
    """The number a string write delivers, read the way the EPICS client reads it.

    A string written to a numeric channel is converted into the channel's own
    type by C code, not by Python, and C's reading of a numeral is not
    ``float()``'s. An integer field takes ``strtol`` with base 0, so ``"0x10"``
    is 16 and ``"010"`` is 8; a floating-point field takes ``strtod``, so
    ``"0x10"`` is 16 there too but ``"010"`` is 10, and ``"1e3"`` is 1000. ``"1_000"``, ``"1,000"`` and ``"0b11"`` are errors in
    both. Measured against a soft IOC.

    The validator does not know the channel's type, so a string is accepted
    only when every reading that succeeds gives the same number; ``"010"`` is
    refused as ambiguous. That makes it exactly as permissive as the C rules
    or stricter, never looser. The EPICS connector does not leave the
    conversion to the IOC, which would stop at the first character it cannot
    read and store ``"1e3"`` in an integer field as 1: it reads the text by the
    rule for the channel's own field type (:func:`c_numeral`) and refuses text
    that rule cannot read, so every string accepted here and written lands as
    the number it was checked as.

    ``nan``, ``inf`` and ``infinity`` (which ``strtod`` takes) are not numerals
    here and are refused, like their float counterparts.
    """
    text = value.strip(_C_WHITESPACE)
    integer = _c_integer(text)
    floating = _c_float(text)
    readings = {float(r) for r in (integer, floating) if r is not None}
    if not readings:
        return None, (
            f"String value {value!r} is not a finite decimal or hexadecimal numeral, so "
            f"it cannot be checked against this channel's numeric limits. Write a number "
            f"instead"
        )
    if len(readings) > 1:
        return None, (
            f"String value {value!r} is ambiguous: the control system reads it as "
            f"{integer} into an integer channel and {floating} into a floating-point "
            f"one. Write a number instead"
        )
    return readings.pop(), None


def _finite_real_or_reason(value: object) -> tuple[float | None, str | None]:
    """The value as a finite ``float``, or why it cannot be held to a numeric limit.

    A real number is accepted as is: ``int``, ``float``, ``bool`` and anything
    registered as :class:`numbers.Real` (numpy scalars included). A ``str`` is
    accepted when it is a numeral the EPICS client would turn into one number
    whatever the channel's type -- see :func:`_numeral_or_reason` -- and is
    checked as that number. Everything else (``bytes``, lists, ``None``,
    complex) is refused.

    NaN and infinity are refused too: NaN fails every comparison, so it would
    pass any ``min_value``/``max_value``/``max_step``, and an infinity is not a
    setpoint any limit was written to admit.

    Returns:
        ``(number, None)`` for an acceptable value, ``(None, reason)`` otherwise.
    """
    if isinstance(value, str):
        number, reason = _numeral_or_reason(value)
        if number is None:
            return None, reason
    elif isinstance(value, numbers.Real):
        number = float(value)
    else:
        return None, (
            f"Value of type {type(value).__name__} is not a real number, so it cannot "
            f"be checked against this channel's numeric limits"
        )
    if not math.isfinite(number):
        return None, (
            f"Value {number} is not finite, so it cannot be checked against this "
            f"channel's numeric limits"
        )
    return number, None


def _is_json_object(value: object) -> TypeGuard[dict[str, object]]:
    """Whether ``value`` is a JSON object: a ``dict``, whose keys :mod:`json` makes ``str``."""
    return isinstance(value, dict)


[docs] def step_read_timeout_seconds( config: Mapping[str, object] | None, connector_type: str | None = None ) -> float: """The ``max_step`` fresh-read budget one connector block declares. Args: config: A connector's own config section — the mapping ``control_system.connector.<type>`` resolves to. connector_type: 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 :data:`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. """ if not isinstance(config, Mapping): return DEFAULT_STEP_READ_TIMEOUT_SECONDS declared = config.get(STEP_READ_TIMEOUT_KEY) if declared is None: return DEFAULT_STEP_READ_TIMEOUT_SECONDS if isinstance(declared, bool) or not isinstance(declared, int | float) or declared <= 0: logger.warning( "control_system.connector.%s.%s must be a positive number of seconds, " "got %r — falling back to %s", connector_type or "<type>", STEP_READ_TIMEOUT_KEY, declared, DEFAULT_STEP_READ_TIMEOUT_SECONDS, ) return DEFAULT_STEP_READ_TIMEOUT_SECONDS return float(declared)
[docs] def mapping_config_lookup(config: Mapping[str, object]) -> ConfigLookup: """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. Args: config: 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. """ def lookup(path: str, default: object = None) -> object: value: object = config for key in path.split("."): if not isinstance(value, Mapping) or key not in value: return default value = value[key] return value return lookup
[docs] @dataclass class ChannelLimitsConfig: """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 # Optional: requires channel read (I/O overhead) writable: bool = dataclass_field(kw_only=True)
[docs] class LimitsValidator: """Core limits validation engine. Performs synchronous validation - no async I/O to keep it simple. Raises exceptions directly instead of returning result objects. """
[docs] def __init__( self, limits_database: dict[str, ChannelLimitsConfig], policy_config: Mapping[str, object], raw_db: Mapping[str, object] | None = None, failsafe_reason: str | None = None, ) -> None: self.limits = limits_database self.policy = policy_config # Keep raw database for confirm-policy access; none given is an empty one. self._raw_db: Mapping[str, object] = {} if raw_db is None else raw_db # Set only by the empty-DB failsafe paths in from_config: the database # could not be loaded, so every write is blocked. validate() uses it to # refuse with a load-failure message instead of the unlisted-channel # one — the two conditions need different operator responses. self.failsafe_reason = failsafe_reason
[docs] @staticmethod def resolve_database_path( db_path: str, project_root: str | None, config_path: str | None = None ) -> str: """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 :func:`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. """ db_path_obj = Path(db_path) if db_path_obj.is_absolute(): return db_path if config_path: return str(Path(config_path).parent / db_path) config_file = os.environ.get("CONFIG_FILE") if config_file: return str(Path(config_file).parent / db_path) if project_root: return str(Path(project_root) / db_path) return db_path
[docs] @classmethod def configured_database_path( cls, *, config_lookup: ConfigLookup | None = None, config_path: str | None = None, ) -> str | None: """The file :data:`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 :meth:`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. Args: config_lookup: Where the key is read from, with the signature of :func:`osprey_connectors.config.get_config_value`. Defaults to that function, which reads the live configurable; pass :func:`mapping_config_lookup` for a config held as a dict. config_path: The config file the lookup answers from, which is the anchor a relative path resolves against (see :meth:`resolve_database_path`). Defaults to :func:`osprey_connectors.config.default_config_path` when the lookup is the live one; a caller supplying its own lookup names its own anchor, or leaves it to the fallbacks. Returns: The resolved path as a string, or ``None``. """ if config_lookup is None: from osprey_connectors.config import default_config_path, get_config_value # Bound through a ConfigLookup, so the lookup answers ``object``. live_lookup: ConfigLookup = get_config_value config_lookup = live_lookup if config_path is None: config_path = default_config_path() raw = config_lookup(LIMITS_DATABASE_CONFIG_KEY, None) if not isinstance(raw, str) or not raw.strip(): return None project_root = config_lookup(_PROJECT_ROOT_CONFIG_KEY, None) return cls.resolve_database_path( str(Path(raw.strip()).expanduser()), project_root if isinstance(project_root, str) else None, config_path=config_path, )
[docs] @classmethod def load_configured_database( cls, *, config_lookup: ConfigLookup | None = None, config_path: str | None = None, ) -> tuple[tuple[dict[str, ChannelLimitsConfig], dict[str, object]] | None, str | None]: """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. Args: config_lookup: As for :meth:`configured_database_path`. config_path: As for :meth:`configured_database_path`. Returns: A ``(loaded, reason)`` pair with exactly one half set: either the ``(limits_database, raw_database)`` tuple, or a sentence naming what could not be read, complete enough to be quoted by any caller. """ db_path = cls.configured_database_path(config_lookup=config_lookup, config_path=config_path) if db_path is None: return None, f"{LIMITS_DATABASE_CONFIG_KEY} is not configured" try: limits_db, raw_db = cls._load_limits_database(db_path) except ValueError as e: return None, ( f"the limits database at {db_path} ({LIMITS_DATABASE_CONFIG_KEY}) could not " f"be read or parsed: {e}" ) logger.debug(f"Loaded limits database with {len(limits_db)} channels from {db_path}") return (limits_db, raw_db), None
[docs] @staticmethod def writable_addresses(db_path: str | Path) -> frozenset[str]: """The addresses a limits database declares writable. Read through :meth:`_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. Args: db_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. """ limits_db, _raw = LimitsValidator._load_limits_database(str(db_path)) return frozenset(address for address, entry in limits_db.items() if entry.writable)
[docs] @classmethod def from_config( cls, *, connector_type: str | None = None, target: str | None = None, ) -> "LimitsValidator | None": """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. Args: connector_type: The connector type to resolve the posture for, as the config's ``control_system.connector`` table keys it. target: The session control target to resolve the posture for, one of :data:`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``. """ if connector_type is not None and target is not None: raise TypeError( "LimitsValidator.from_config() takes connector_type or target, not both: " "a target resolves to a connector type, so passing both states the " "posture twice" ) try: from osprey_connectors.config import get_config_value section: object = get_config_value("control_system", {}) except (FileNotFoundError, KeyError, RuntimeError) as e: # Config not available (test environment, etc.) - limits checking disabled logger.debug(f"Limits validator not initialized (config unavailable): {e}") return None if target is not None: posture = target_limits_posture(section, target) else: posture = type_limits_posture(section, connector_type) return cls._from_posture(posture)
[docs] @classmethod def from_config_most_restrictive(cls) -> "LimitsValidator | None": """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 :func:`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 :meth:`from_config` returns, for the same reasons. """ try: from osprey_connectors.config import get_config_value section: object = get_config_value("control_system", {}) except (FileNotFoundError, KeyError, RuntimeError) as e: # Config not available (test environment, etc.) - limits checking disabled logger.debug(f"Limits validator not initialized (config unavailable): {e}") return None return cls._from_posture(most_restrictive_limits_posture(section))
@classmethod def _from_posture(cls, posture: LimitsPosture) -> "LimitsValidator | None": """Build a validator for an already-resolved limits posture. The caller resolves the posture for the thing it is acting on — a connector for its own type, a tool or hook for the recorded control target — and this turns that answer into an enforcing validator. The posture's answering key travels into ``policy`` so that a later refusal names the config line an operator can edit: on a deployment that runs its simulator alone ``optional``, quoting the deployment-wide key would send them to flip a line the per-type block overrides. An incomplete block is checked before ``enabled``, and on purpose. Such a block answered neither leaf, so ``enabled`` is ``None`` and the disabled branch would wave every write through on exactly the config nobody has finished writing. Blocking instead is the same choice the missing-database-path branch makes. A block is incomplete two ways, and the second is why this branch comes first. A per-type block may omit a leaf. Either block may write one as something no reader can use — a quoted ``'true'``, a ``1``, an unexpanded ``'${LIMITS_ON}'``, which is the shape environment expansion leaves behind when nothing set the variable. That second one is a deployment trying to switch limits checking *on*; reading it as an unset ``enabled`` would take the disabled branch and check nothing. Whether the database must exist is :func:`~osprey_connectors.types.limits_database_required`, asked of the live config's path. ``optional`` with no path configured needs none: the validator enforces over an empty database, so every channel is unlisted and written with no limits. A configured path that fails to load stays fail-safe whatever the mode. Args: posture: The resolved posture, from the ``types`` resolver family. Returns: An enforcing validator (over an empty database for ``optional`` with no path configured); a fail-safe validator that blocks every write when the block is incomplete or a required database is unavailable; or ``None`` when limits checking is off for this posture or the config could not be read at all. """ try: if posture.incomplete: reason = ( f"{posture.block_key} does not state " f"{', '.join(posture.incomplete)} as a readable value" ) logger.warning(f"Incomplete limits block - blocking all writes: {reason}") return cls({}, {}, {}, failsafe_reason=reason) if posture.enabled is not True: return None # Both entries are JSON-serialisable: the python executor embeds # this dict verbatim into the sandbox (wrapper.py), so the # tri-state rides as null rather than as anything richer. policy: dict[str, object] = { "mode": posture.mode, "mode_key": posture.key("mode"), } if not limits_database_required( posture, path_configured=cls.configured_database_path() is not None ): return cls({}, policy, {}) loaded, load_reason = cls.load_configured_database() if loaded is None: # Same failsafe as the incomplete-block case above: a missing # or unparseable database must never crash the connector (a # read-only deployment needs no limits) nor silently disable # checking (returning None would leave writes unchecked) -- an # empty DB blocks every write with a clear refusal instead. logger.warning(f"Limits checking enabled but {load_reason} - blocking all writes") return cls( {}, {}, {}, failsafe_reason=f"limits checking is enabled but {load_reason}" ) limits_db, raw_db = loaded return cls(limits_db, policy, raw_db) except (FileNotFoundError, KeyError, RuntimeError) as e: # Config not available (test environment, etc.) - limits checking disabled logger.debug(f"Limits validator not initialized (config unavailable): {e}") return None
[docs] def resolve_confirm(self, channel_address: str) -> bool: """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 :class:`ChannelLimitsConfig`. Args: channel_address: Channel address being written Returns: True when the write must be confirmed (the fleet default). """ raw_db = self._raw_db if not isinstance(raw_db, dict): return True channel_config = raw_db.get(channel_address) if _is_json_object(channel_config) and "confirm" in channel_config: return bool(channel_config["confirm"]) return True
[docs] def measures_step(self, channel_address: str) -> bool: """Whether :meth:`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. """ channel_config = self.limits.get(channel_address) return channel_config is not None and channel_config.max_step is not None
@staticmethod def _numeric_field(config_dict: Mapping[str, object], field: str) -> float | None: """One numeric field of a channel entry; ``None`` when absent or null. Raises: ValueError: The field holds something that is not a number. """ value = config_dict.get(field) if value is not None and not isinstance(value, (int, float)): raise ValueError( f"Field '{field}' must be numeric, got {type(value).__name__} = {value}" ) return value @staticmethod def _boolean_field(config_dict: Mapping[str, object], field: str) -> bool | None: """One boolean field of a channel entry; ``None`` when absent. Raises: ValueError: The field is present and is not a boolean. """ if field not in config_dict: return None value = config_dict[field] if not isinstance(value, bool): raise ValueError( f"Field '{field}' must be boolean, got {type(value).__name__} = {value}" ) return value @staticmethod def _validate_channel_config(channel_name: str, config_dict: Mapping[str, object]) -> None: """Validate a single channel configuration structure. Args: channel_name: Channel address being validated config_dict: Configuration dictionary for the channel Raises: ValueError: If configuration is invalid with descriptive error message """ valid_fields = {"min_value", "max_value", "max_step", "writable", "confirm"} # Any '_'-prefixed key is documentation metadata and stays legal, whatever # it is called. Every other unrecognised key fails the load: a limits file # is a safety artifact, and a key the loader does not understand is a key # whose intent was never applied. unknown_fields = {k for k in config_dict if not k.startswith("_")} - valid_fields if unknown_fields: detail = ( f"Channel '{channel_name}' has unknown fields: {sorted(unknown_fields)}. " f"Valid fields are: {sorted(valid_fields)}" ) if "verification" in unknown_fields: raise ValueError( f"Channel '{channel_name}': 'verification' was replaced by " f"'confirm: true|false'. {detail}" ) raise ValueError(detail) # Validate numeric fields for field in ["min_value", "max_value", "max_step"]: LimitsValidator._numeric_field(config_dict, field) # Validate boolean fields for field in ["writable", "confirm"]: LimitsValidator._boolean_field(config_dict, field) @staticmethod def _load_limits_database( db_path: str, ) -> tuple[dict[str, ChannelLimitsConfig], dict[str, object]]: """Load and validate limits database from JSON file. The database holds: - One entry per channel, each stating its own ``writable``; an entry without it fails the load - Metadata fields with underscore prefix (_comment, _version, etc.) - Per-channel confirm policy (stored in raw DB) Every other top-level key is a channel address, except ``defaults``, which fails the load: no block of shared values applies to an entry. Args: db_path: Path to JSON database file Returns: Tuple of (parsed_limits_db, raw_db): - parsed_limits_db: Dict mapping channel addresses to ChannelLimitsConfig - raw_db: Raw dict from JSON file (for confirm-policy access) Raises: ValueError: If database structure is invalid """ try: path = Path(db_path).expanduser() if not path.exists(): logger.error(f"Limits database not found: {db_path}") raise ValueError(f"Channel limits database not found: {db_path}") with open(path) as f: raw_db: object = json.load(f) if not _is_json_object(raw_db): raise ValueError( f"Limits database must be a JSON object/dict, got {type(raw_db).__name__}" ) # Every entry states its own write policy; a shared block would # hand writability to entries that never asked for it. if "defaults" in raw_db: raise ValueError( "Top-level key 'defaults' is not allowed: each channel entry " "states its own 'writable' and 'confirm'" ) # Load channel configurations limits_db: dict[str, ChannelLimitsConfig] = {} for channel_name, config_dict in raw_db.items(): # Skip metadata fields (underscore prefix) if channel_name in METADATA_FIELDS or channel_name.startswith("_"): logger.debug(f"Skipping metadata field: {channel_name}") continue # Validate it's a dict if not _is_json_object(config_dict): raise ValueError( f"Invalid config for channel '{channel_name}': " f"must be a dictionary, got {type(config_dict).__name__}" ) try: # Validate configuration structure LimitsValidator._validate_channel_config(channel_name, config_dict) # Writability is never assumed: an entry that does not # state it fails the load. writable = LimitsValidator._boolean_field(config_dict, "writable") if writable is None: raise ValueError(f"Channel '{channel_name}' does not state 'writable'") config = ChannelLimitsConfig( channel_address=channel_name, min_value=LimitsValidator._numeric_field(config_dict, "min_value"), max_value=LimitsValidator._numeric_field(config_dict, "max_value"), max_step=LimitsValidator._numeric_field(config_dict, "max_step"), writable=writable, ) # Log performance warning for max_step if config.max_step is not None: logger.debug( f"Channel '{channel_name}' has max_step={config.max_step} configured " f"(will require channel read, adds ~50-100ms latency)" ) limits_db[channel_name] = config except (TypeError, ValueError, KeyError) as e: # One malformed entry fails the whole load. Skipping it used # to drop the channel from the database, which - under # the optional mode - silently removed its limits. raise ValueError(f"Invalid config for channel '{channel_name}': {e}") from e logger.info(f"Successfully loaded {len(limits_db)} channel configurations") logger.debug(f"Channel limits database: {db_path}") return limits_db, raw_db except json.JSONDecodeError as e: logger.error("=" * 80) logger.error("CRITICAL: CHANNEL LIMITS DATABASE HAS INVALID JSON") logger.error(f" File: {db_path}") logger.error(f" Error: {e}") logger.error(" Impact: ALL channel writes will be BLOCKED (fail-safe mode)") logger.error(" Fix: Correct the JSON syntax in your limits database file") logger.error("=" * 80) raise ValueError(f"Invalid JSON in channel limits database: {e}") from e except Exception as e: logger.error(f"Failed to load limits database: {e}") raise ValueError(f"Failed to load channel limits database: {e}") from e
[docs] def validate( self, channel_address: str, value: object, *, read_current: CurrentValueReader | None = None, ) -> None: """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. Args: channel_address: Channel address to validate value: Value to write read_current: 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 """ from osprey_connectors.errors import ChannelLimitsViolationError channel_config, numeric_value = self._validate_without_step(channel_address, value) if channel_config is None or numeric_value is None: # A channel with no record under the optional mode, or a channel with no numeric limit: # neither one has a step size to measure. return # Check 4: Step size limit (OPTIONAL - only if configured, requires I/O) if channel_config.max_step is not None: if read_current is None: # FAILSAFE: no reader, no measurement, no write. This used to # be a direct pyepics caget, which measured the step over # Channel Access whatever control system the write was bound # for -- so max_step blocked every write on a non-CA # deployment, and on a CA one it followed the process-wide # EPICS_CA_* environment rather than the client the write # itself goes through. logger.error( f"Cannot verify step size for {channel_address} - " f"the caller supplied no way to read the channel" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="STEP_CHECK_FAILED", violation_reason=( "No way to read the current channel value was supplied, " "so the step size cannot be verified" ), ) try: # Read current value (I/O operation) logger.debug(f"Reading current value for step check: {channel_address}") current_value = read_current(channel_address) if current_value is None: # FAILSAFE: Can't read current value → block write logger.warning( f"Cannot verify step size for {channel_address} - " f"channel read returned None" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="STEP_CHECK_FAILED", violation_reason="Cannot read current channel value to verify step size", ) # FAILSAFE: a present value that is not a finite real number # (NaN from a disconnected record, a label, a waveform) gives # no step to measure, and a step that cannot be measured # cannot be approved. NaN in particular would pass the # comparison below whatever the requested value. numeric_current, current_reason = _finite_real_or_reason(current_value) if numeric_current is None: logger.warning( f"Cannot verify step size for {channel_address} - " f"current value {current_value!r} is not a finite number" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="STEP_CHECK_FAILED", violation_reason=( f"Cannot verify step size: current channel value " f"{current_value!r} is not a finite real number ({current_reason})" ), current_value=current_value, max_step=channel_config.max_step, min_value=channel_config.min_value, max_value=channel_config.max_value, ) step_size = abs(numeric_value - numeric_current) if step_size > channel_config.max_step: logger.warning( f"Blocked write exceeding max step: {channel_address} " f"step={step_size:.3f} > max={channel_config.max_step}" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="MAX_STEP_EXCEEDED", violation_reason=( f"Step size {step_size:.3f} exceeds maximum " f"{channel_config.max_step} (current={numeric_current}, " f"requested={numeric_value})" ), current_value=current_value, max_step=channel_config.max_step, min_value=channel_config.min_value, max_value=channel_config.max_value, ) except ChannelLimitsViolationError: # Re-raise limits violations (from max_step check) raise except Exception as e: # FAILSAFE: Any error during read → block write logger.error( f"Failed to read current value for step check: {channel_address} - {e}" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="STEP_CHECK_FAILED", violation_reason=f"Channel read failed: {str(e)}", ) from e # All checks passed! logger.debug(f"Validated write: {channel_address}={value}")
[docs] def validate_without_step_check(self, channel_address: str, value: object) -> None: """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 :meth:`validate`. Refusing here for want of a reader would take ``max_step`` off the mediated write path entirely rather than enforcing it. Args: channel_address: Channel address to validate value: Value to write Raises: ChannelLimitsViolationError: If any of those checks fails """ self._validate_without_step(channel_address, value)
def _validate_without_step( self, channel_address: str, value: object ) -> tuple[ChannelLimitsConfig | None, float | None]: """Checks 1-3, shared by both entry points. Returns the channel's config and the value as a number, so the caller can go on to the step check without repeating the lookup. A ``None`` config means a channel with no record under the optional mode and a ``None`` number means a channel with no numeric limit -- in either case there is nothing further to check. A channel that has a numeric limit never answers ``None``: a value it cannot hold to that limit is refused here. """ from osprey_connectors.errors import ChannelLimitsViolationError # Check 1: Channel exists in database? channel_config = self.limits.get(channel_address) if channel_config is None: # A database that failed to load blocks everything — say so, rather # than refusing with the unlisted-channel message: "not in limits # database" sends the operator chasing a data problem when the # actual failure is that no database was loaded at all. if self.failsafe_reason: logger.warning( f"Blocked write (limits database unavailable): {channel_address}={value}" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="LIMITS_DATABASE_UNAVAILABLE", violation_reason=( f"Limits database unavailable — all writes are blocked as a " f"failsafe ({self.failsafe_reason}). This is not a statement " f"about channel '{channel_address}'." ), ) # No record - the mode decides. Only an explicit `optional` is # permission: the policy carries the posture's mode verbatim so # that `channel_limits` can report an unstated answer as `null`, # and unstated is nobody's permission to write a channel with no # record. if self.policy.get("mode") == LIMITS_MODE_OPTIONAL: return None, None # Written with no limits # FAILSAFE: refuse a channel with no record. Name the key that # actually answered — a deployment may set this per connector # type, and quoting the deployment-wide key there would send an # operator to flip a line the per-type block overrides. A # validator built from a bare policy dict carries no key; the # deployment-wide one is the honest answer for it. answering_key = self.policy.get("mode_key", "control_system.limits_checking.mode") logger.warning(f"Blocked write to unlisted channel: {channel_address}={value}") raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="UNLISTED_CHANNEL", violation_reason=( f"Channel '{channel_address}' not in limits database " f"('{answering_key}' is not '{LIMITS_MODE_OPTIONAL}')" ), ) # Check 2: Channel is writable? if not channel_config.writable: logger.warning(f"Blocked write to read-only channel: {channel_address}={value}") raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="READ_ONLY_CHANNEL", violation_reason="Channel is marked as read-only", ) # Check 3: Min/Max bounds. # # The rule: a channel with ANY numeric limit (min_value, max_value or # max_step) accepts only a finite real number, or a string the EPICS # client parses to one unambiguously. Anything else -- a string it # would read differently by channel type, NaN, an infinity, a list, # None -- is refused rather than waved past the numeric checks, because # a value the validator cannot compare is a value it has not checked. # See `_numeral_or_reason` for how strings are read. # # A channel with no numeric limit (a writable-only entry, e.g. an enum # or string record written by label) has nothing numeric to hold the # value to, so it passes as it always has. if ( channel_config.min_value is None and channel_config.max_value is None and channel_config.max_step is None ): return channel_config, None numeric_value, reason = _finite_real_or_reason(value) if numeric_value is None: logger.warning(f"Blocked non-numeric write: {channel_address}={value!r}") raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type=INVALID_NUMERIC_VALUE, violation_reason=reason or "Value is not a finite real number", min_value=channel_config.min_value, max_value=channel_config.max_value, max_step=channel_config.max_step, ) if channel_config.min_value is not None and numeric_value < channel_config.min_value: logger.warning( f"Blocked write below minimum: {channel_address}={numeric_value} " f"(min={channel_config.min_value})" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="MIN_EXCEEDED", violation_reason=f"Value {numeric_value} below minimum {channel_config.min_value}", min_value=channel_config.min_value, max_value=channel_config.max_value, ) if channel_config.max_value is not None and numeric_value > channel_config.max_value: logger.warning( f"Blocked write above maximum: {channel_address}={numeric_value} " f"(max={channel_config.max_value})" ) raise ChannelLimitsViolationError( channel_address=channel_address, value=value, violation_type="MAX_EXCEEDED", violation_reason=f"Value {numeric_value} above maximum {channel_config.max_value}", min_value=channel_config.min_value, max_value=channel_config.max_value, ) return channel_config, numeric_value