Coverage for core / src / sensorkit / sensor / client.py: 100%
63 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"""Connect a sensor session and plan workflows independently of execution.
4 session = await Sensor.connect(definition, sensorkit)
5 workflow = session.plan_lifecycle(definition.tables[0])
6 report = await session.execute(workflow)
8The session accepts lifecycle tables and collect intents directly. To use
9policies, compose their deadline rules before connecting, then compose tables
10against the bound sensor. Standard-task translation is also optional.
11"""
13from __future__ import annotations
15import weakref
16from collections.abc import Mapping
18import sensorkit.api as sk
19from sensorkit.backend.base import KeyNotFound
20from sensorkit.common.aio import AsyncObserver
21from sensorkit.common.keyword import KeywordDict
22from sensorkit.core.entity import DeviceDetails
23from sensorkit.sensor.binding import BoundSensor
24from sensorkit.sensor.collect import CollectIntent, compile_collect, pack
25from sensorkit.sensor.definition import SensorDefinition
26from sensorkit.sensor.dispatch import DeviceContexts, InstrumentContexts, OperationEvent
27from sensorkit.sensor.execution import (
28 AbortPredicate,
29 ExecutionState,
30 WorkflowExecutor,
31 WorkflowReport,
32)
33from sensorkit.sensor.lifecycle import LifecycleWorkflow, compile_lifecycle
34from sensorkit.sensor.workflow import ExecutableWorkflow, OperatorRule
37class Sensor:
38 """A connected sensor that plans workflows and executes them one at a time.
40 Only workflows planned by this session may execute through it. Discarded
41 plans are not retained. Callers must not mutate the definition, binding or
42 compiled workflows. The session checks workflow identity without checking
43 for mutations to nested values.
44 """
46 def __init__(
47 self, definition: SensorDefinition, sensor: BoundSensor, executor: WorkflowExecutor
48 ):
49 self._definition = definition
50 self._sensor = sensor
51 self._executor = executor
52 self._issued: weakref.WeakSet[ExecutableWorkflow] = weakref.WeakSet()
53 self._running = False
55 @property
56 def definition(self) -> SensorDefinition:
57 """Return the definition supplying this session's structure and
58 deadline rules.
59 """
60 return self._definition
62 @property
63 def sensor(self) -> BoundSensor:
64 """Return the bound sensor used for planning and execution."""
65 return self._sensor
67 @property
68 def executor(self) -> WorkflowExecutor:
69 """Return the executor and its operation-event observer.
71 Calling it directly bypasses session issuance and overlap checks.
72 """
73 return self._executor
75 @classmethod
76 async def connect(cls, definition: SensorDefinition, sensorkit: sk.SensorKit) -> Sensor:
77 """Validate the definition, discover configured devices and bind
78 their capabilities.
80 Validate the definition before reading device capability details. The caller owns
81 the supplied client and backend and remains responsible for closing
82 them.
84 Args:
85 definition: Authored definition with any generated deadlines
86 composed.
87 sensorkit: Client used to access configured devices.
89 Returns:
90 A session bound to the discovered device details.
92 Raises:
93 ValueError: The definition is invalid, capability details are missing,
94 an entity is not a device, or a declared trait is unregistered
95 or unsatisfied.
96 BackendError: Device capability details could not be read from the backend.
97 """
98 topology = definition.check()
99 keys = tuple(p.device for p in topology.placements())
100 clients = {key: sensorkit.device(key) for key in keys}
101 reported: dict[str, DeviceDetails] = {}
103 for key, client in clients.items():
104 try:
105 details = await client.get_details()
106 except KeyNotFound:
107 continue
109 reported[key] = details
111 # Report all missing devices in one binding error.
112 sensor = BoundSensor.bind(topology, reported)
113 executor = WorkflowExecutor(sensor, clients, events=AsyncObserver[OperationEvent]())
115 return cls(definition, sensor, executor)
117 def plan_lifecycle(
118 self, workflow: LifecycleWorkflow, *, rules: tuple[OperatorRule, ...] = ()
119 ) -> ExecutableWorkflow:
120 """Compile and issue a lifecycle table using this definition's
121 deadlines.
123 Optional operator rules come from the caller. No commands are sent.
125 Raises:
126 ValueError: The table cannot compile against this sensor.
127 """
128 return self._issue(
129 compile_lifecycle(
130 workflow, self._sensor, deadlines=self._definition.deadlines, rules=rules
131 )
132 )
134 def plan_collect(
135 self,
136 intent: CollectIntent,
137 *,
138 rules: tuple[OperatorRule, ...] = (),
139 device_keywords: Mapping[str, KeywordDict] | None = None,
140 ) -> ExecutableWorkflow:
141 """Pack, compile and issue a collect intent using this definition's
142 deadlines.
144 `device_keywords` supplies the keywords for planning selections. A
145 missing mapping, device or keyword is treated as absent. Operator rules
146 use the session's binding independently of this mapping. Planning
147 chooses all hardware before any commands are sent.
149 Raises:
150 ValueError: The intent cannot pack or compile against this sensor.
151 """
152 bound = pack(intent, self._sensor, device_keywords=device_keywords)
154 return self._issue(
155 compile_collect(bound, self._sensor, deadlines=self._definition.deadlines, rules=rules)
156 )
158 async def execute(
159 self,
160 workflow: ExecutableWorkflow,
161 *,
162 contexts: DeviceContexts | None = None,
163 instrument_contexts: InstrumentContexts | None = None,
164 base: sk.Context | None = None,
165 in_domain: AbortPredicate | None = None,
166 state: ExecutionState | None = None,
167 ) -> WorkflowReport:
168 """Run an issued workflow, keeping the session occupied through
169 cleanup and drain.
171 Overlapping runs are rejected.
173 Args:
174 workflow: Workflow planned by this session.
175 contexts: Current device contexts, sampled for each acquisition.
176 instrument_contexts: Resolve controller keywords for each capture target.
177 base: Context shared by every acquisition in the run.
178 in_domain: Predicate recognizing cancellations as domain aborts.
179 state: Fresh caller-owned state for inspection after hard
180 cancellation.
182 Returns:
183 The executor's aggregate workflow report.
185 Raises:
186 ValueError: The workflow was not issued here, another run is
187 active, or state was already used. Refusal dispatches nothing
188 and preserves state.
189 WorkflowError: Required main work failed or did not run, or
190 required cleanup failed without a domain abort.
191 asyncio.CancelledError: A declined cancellation, after local work
192 drains.
193 """
194 # Check issuance and overlap before yielding or touching execution state.
195 if workflow not in self._issued:
196 raise ValueError(
197 f"{workflow.name}: this session did not issue the workflow; "
198 f"plan it through the session that runs it"
199 )
201 if self._running:
202 raise ValueError(f"{workflow.name}: another run on this session has not ended")
204 self._running = True
206 try:
207 return await self._executor.execute(
208 workflow,
209 contexts=contexts,
210 instrument_contexts=instrument_contexts,
211 base=base,
212 in_domain=in_domain,
213 state=state,
214 )
215 finally:
216 self._running = False
218 def _issue(self, workflow: ExecutableWorkflow) -> ExecutableWorkflow:
219 """Register a workflow by identity without retaining it strongly."""
220 self._issued.add(workflow)
222 return workflow