Coverage for core / src / sensorkit / sensor / routing.py: 100%
75 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"""Route commands to supporting placements on participating instrument chains.
4Sensor subjects use one common target; instrument subjects route per chain,
5merging duplicate targets. Scope and selection filters narrow the candidates.
6Capability checks and selections read the bound sensor given to the router,
7including any device keywords it holds for planning.
8"""
10from __future__ import annotations
12from dataclasses import dataclass
13from typing import Literal
15from sensorkit.core.device import DeviceCommand
16from sensorkit.sensor.binding import BoundSensor
17from sensorkit.sensor.selection import Selection
18from sensorkit.sensor.topology import Placement, format_paths
20type Scope = Literal["any", "private", "shared"]
21"""Filter routing candidates by their relation to an instrument.
23`private` uses the topology's local, sole-reader placements; `shared` uses the
24rest of the chain. `any` accepts both. Ancestor infrastructure remains shared
25even when it has only one reader.
26"""
28type Subject = Literal["sensor", "instrument"]
29"""Choose how participants are grouped and targets are ranked for routing.
31`sensor` chooses the shallowest supporting device common to all participants.
32`instrument` chooses the deepest supporting device on each participant's chain.
33Shared targets are commanded once. `Scope` filters candidates independently.
34"""
37def partition(
38 subject: Subject, participants: tuple[Placement, ...]
39) -> tuple[tuple[Placement, ...], ...]:
40 """Group all sensor participants together, or each instrument
41 separately.
42 """
43 match subject:
44 case "sensor":
45 return (participants,)
46 case "instrument":
47 return tuple((p,) for p in participants)
50@dataclass(frozen=True)
51class RoutedCommand:
52 """A command with its target placement and optional explicit timeout.
54 Routing chooses the target; graph compilation resolves the timeout against deadline
55 rules. The timeout is orchestration metadata, not part of the device
56 command.
57 """
59 target: Placement
60 command: DeviceCommand
61 timeout_s: float | None = None
63 @property
64 def governs(self) -> tuple[Placement, type[DeviceCommand]]:
65 """Return the target placement and command type governing collect state."""
66 return self.target, type(self.command)
69class CommandRouter:
70 """Choose command targets on a bound sensor."""
72 def __init__(self, sensor: BoundSensor):
73 self.sensor = sensor
75 def supported_on(self, command: str, participants: tuple[Placement, ...]) -> bool:
76 """Test whether any device on the participating chains supports the
77 command.
78 """
79 return any(
80 command in self.sensor.supported_commands(placement.device)
81 for placement in self._reachable(participants)
82 )
84 def route(
85 self,
86 command: DeviceCommand,
87 subject: Subject,
88 participants: tuple[Placement, ...],
89 *,
90 select: Selection | None = None,
91 scope: Scope = "any",
92 device: str | None = None,
93 ) -> tuple[RoutedCommand, ...]:
94 """Choose targets for a command and return one routed command per
95 target.
97 A sensor subject chooses the shallowest supporting placement common to
98 all participants. An instrument subject chooses the deepest supporting
99 placement on each participant's chain. Repeated targets are commanded
100 once.
102 `scope` filters private or shared placements; `select` applies an
103 additional predicate. `device` restricts the search to a named device,
104 which must still satisfy capability, scope and selection checks.
106 Raises:
107 ValueError: No eligible target supports the command, candidates tie
108 at the winning depth, or a named device is outside the relevant
109 chains.
110 """
111 targets = dict.fromkeys(
112 self._winner(command, subject, group, select, scope, device)
113 for group in partition(subject, participants)
114 )
116 return tuple(RoutedCommand(target=target, command=command) for target in targets)
118 def _winner(
119 self,
120 command: DeviceCommand,
121 subject: Subject,
122 participants: tuple[Placement, ...],
123 select: Selection | None,
124 scope: Scope,
125 device: str | None,
126 ) -> Placement:
127 """Choose one target for a participant group using filters and
128 depth.
129 """
130 sensor = self.sensor
131 named = type(command).model_tag()
132 reachable = self._reachable(participants)
134 if device is not None:
135 reachable = self._named(device, reachable, named, participants)
137 candidates = tuple(
138 p
139 for p in reachable
140 if named in sensor.supported_commands(p.device)
141 and any(self._eligible(p, q, scope) for q in participants)
142 and (select is None or select.matches(p, sensor))
143 )
145 if not candidates:
146 raise ValueError(
147 f"no device on {format_paths(participants)} supports '{named}'"
148 + ("" if scope == "any" else f" as a {scope} device")
149 + ("" if select is None else " and satisfies the selection")
150 )
152 if subject == "sensor":
153 candidates = self._covering(candidates, participants, named)
155 best = (min if subject == "sensor" else max)(p.depth for p in candidates)
156 winners = sorted(
157 (p for p in candidates if p.depth == best), key=lambda p: (p.path, p.device)
158 )
160 if len(winners) > 1:
161 # Equal depths are ambiguous; require an explicit routing choice.
162 raise ValueError(
163 f"'{named}' is supported by "
164 f"{', '.join(repr(p.device) for p in winners)} at the same "
165 f"position on {format_paths(participants)}; name one with device, or "
166 f"set a scope"
167 )
169 return winners[0]
171 def _reachable(self, participants: tuple[Placement, ...]) -> tuple[Placement, ...]:
172 """Combine participant chains, retaining each placement on its first
173 occurrence.
174 """
175 topology = self.sensor.topology
177 return tuple(dict.fromkeys(p for q in participants for p in topology.chain(q)))
179 def _named(
180 self,
181 device: str,
182 reachable: tuple[Placement, ...],
183 named: str,
184 participants: tuple[Placement, ...],
185 ) -> tuple[Placement, ...]:
186 """Restrict reachable placements to an explicitly named device.
188 Raises:
189 ValueError: The device is unreachable or does not support the
190 command.
191 """
192 placement = next((p for p in reachable if p.device == device), None)
194 if placement is None:
195 # An explicit reference must still belong to a participating chain.
196 raise ValueError(f"'{device}' is not on {format_paths(participants)}")
198 if named not in self.sensor.supported_commands(device):
199 raise ValueError(f"'{device}' does not support '{named}'")
201 return (placement,)
203 def _eligible(self, placement: Placement, participant: Placement, scope: Scope) -> bool:
204 """Test chain membership and scope for one participant.
206 Private or shared status is relative to this participant's topology.
207 """
208 topology = self.sensor.topology
210 if placement not in topology.chain(participant):
211 return False
213 match scope:
214 case "private":
215 return placement in topology.private(participant)
216 case "shared":
217 return placement not in topology.private(participant)
219 return True
221 def _covering(
222 self, candidates: tuple[Placement, ...], participants: tuple[Placement, ...], named: str
223 ) -> tuple[Placement, ...]:
224 """Keep only candidates present on every participant's chain.
226 Raises:
227 ValueError: No supporting candidate is common to all chains.
228 """
229 topology = self.sensor.topology
230 common = tuple(p for p in candidates if all(p in topology.chain(q) for q in participants))
232 if not common:
233 raise ValueError(
234 f"'{named}' is supported on {format_paths(participants)}, but by no "
235 f"device every one of them looks through; a sensor-scope "
236 f"command lands on one device or on none"
237 )
239 return common