Coverage for core / src / sensorkit / sensor / definition.py: 100%
42 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2"""Load and validate sensor definitions without contacting devices.
4A definition combines structure, lifecycle tables and deadline rules. Loading
5checks model validity, structural uniqueness, references and symbolic cycles.
6Capability checks and workflow compilation happen after binding.
7"""
9from __future__ import annotations
11from collections.abc import Mapping
12from pathlib import Path
14import yaml
15from pydantic import BaseModel, model_validator
17from sensorkit.sensor.lifecycle import LifecycleWorkflow
18from sensorkit.sensor.topology import Structure, Topology
19from sensorkit.sensor.workflow import DeadlineRule
22class SensorDefinition(BaseModel, frozen=True, extra="forbid"):
23 """A sensor's structure, lifecycle tables and deadline rules.
25 Tables may be supplied as a mapping whose keys supply the table names.
26 Python construction validates the models. Call `check` for structural and
27 reference checks, or use the YAML loaders to perform both.
28 """
30 sensor: Structure
31 tables: tuple[LifecycleWorkflow, ...] = ()
32 deadlines: tuple[DeadlineRule, ...] = ()
34 @model_validator(mode="before")
35 @classmethod
36 def _name_tables_from_keys(cls, v: object) -> object:
37 if not isinstance(v, Mapping) or not isinstance(v.get("tables"), Mapping):
38 return v
40 named = [{**t, "name": k} if isinstance(t, Mapping) else t for k, t in v["tables"].items()]
42 return {**v, "tables": named}
44 @classmethod
45 def from_yaml(cls, text: str) -> SensorDefinition:
46 """Parse a YAML definition and run structural and reference checks.
48 Raises:
49 yaml.YAMLError: The text is not valid YAML.
50 ValidationError: The document does not match the models.
51 ValueError: A structural, reference or dependency check fails.
52 """
53 definition = cls.model_validate(yaml.safe_load(text))
54 definition.check()
56 return definition
58 @classmethod
59 def load(cls, path: str | Path) -> SensorDefinition:
60 """Read a UTF-8 YAML file and validate its definition."""
61 return cls.from_yaml(Path(path).read_text(encoding="utf-8"))
63 def check(self) -> Topology:
64 """Check structure, table names, deadline targets and table
65 dependencies.
67 Checks require no device facts. Compilation later checks selected
68 targets, command support and resolved deadlines against a bound sensor.
70 Returns:
71 The validated topology for binding or further inspection.
73 Raises:
74 ValueError: The structure or references are invalid, table names
75 repeat, a device deadline targets an absent device, or
76 dependencies cycle.
77 """
78 topology = Topology(self.sensor)
79 names = [t.name for t in self.tables]
80 dupes = sorted({n for n in names if names.count(n) > 1})
82 if dupes:
83 raise ValueError(f"a table is named twice: {', '.join(dupes)}")
85 self.check_deadlines(topology)
87 for table in self.tables:
88 table.check()
90 return topology
92 def check_deadlines(self, topology: Topology) -> None:
93 """Check that device-specific deadline rules name configured
94 devices.
96 Raises:
97 ValueError: A rule targets a device absent from the topology.
98 """
99 placed = {placement.device for placement in topology.placements()}
100 unknown = sorted(
101 {
102 rule.target[1]
103 for rule in self.deadlines
104 if rule.target[0] == "device" and rule.target[1] not in placed
105 }
106 )
108 if unknown:
109 raise ValueError(
110 f"deadline rules target devices the structure does not hold: {', '.join(unknown)}"
111 )