Coverage for core / src / sensorkit / sensor / dispatch.py: 98%

161 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Send planned commands, sample acquisition headers and interrupt dropped 

3calls. 

4 

5Operations already contain resolved timeouts and command parameters. For an 

6acquisition, dispatch merges task and planned frame keywords, instrument 

7context, then device snapshots along the chain. It adds this context to a copy 

8of the acquisition command. 

9 

10Record attempts immediately before sending; failures before this point do not 

11arm cleanup. A cancelled or timed-out call triggers one built-in Abort attempt 

12when supported. Record its result separately from the operation's outcome. An 

13acknowledgement confirms a response, not that the hardware stopped. 

14 

15The dispatcher owns and drains both call tasks before releasing its caller. 

16Abort waits up to five seconds for a response, then drains local teardown; 

17caller cancellation does not interrupt that attempt. Operation events go to 

18direct logging and an optional observer with bounded subscriber queues. 

19""" 

20 

21from __future__ import annotations 

22 

23import asyncio 

24from collections.abc import Callable, Mapping 

25from dataclasses import dataclass 

26from typing import Literal 

27 

28from loguru import logger 

29 

30import sensorkit.api as sk 

31from sensorkit.common.aio import AsyncObserver 

32from sensorkit.common.dag import Node 

33from sensorkit.core.device import Abort, DeviceClient, DeviceCommand 

34from sensorkit.data.context import merge_contexts 

35from sensorkit.sensor.binding import BoundSensor 

36from sensorkit.sensor.topology import Placement 

37from sensorkit.sensor.workflow import Operation 

38 

39type DeviceContexts = Callable[[], Mapping[str, sk.Context]] 

40"""Callable supplying current device contexts, sampled for each acquisition.""" 

41 

42type InstrumentContexts = Callable[[Placement], sk.Context] 

43"""Resolve a capture target to its instrument context.""" 

44 

45type OperationOutcome = Literal["begin", "ok", "failed", "cancelled"] 

46 

47type InterruptionOutcome = Literal["acknowledged", "unsupported", "failed", "timed_out"] 

48 

49ABORT_TIMEOUT_S = 5.0 

50"""Abort response timeout in seconds, excluding local call teardown.""" 

51 

52 

53type AttemptRecorder = Callable[[Operation], None] 

54"""Callback recording an operation immediately before its device call 

55starts. 

56 

57`ExecutionState.attempted.add` implements it for cleanup arming by identity. 

58""" 

59 

60type InterruptionRecorder = Callable[[Interruption], None] 

61"""Callback storing one Abort outcome before dispatch returns or raises. 

62 

63Caller-owned storage retains the outcome when cancellation propagates. 

64""" 

65 

66 

67@dataclass(frozen=True) 

68class OperationEvent: 

69 """A begin or terminal event for an attempted operation. 

70 

71 Each attempted operation emits begin followed by ok, failed or cancelled. 

72 `detail` is the return value for ok, the exception for failed, or `None`. 

73 """ 

74 

75 operation: Operation 

76 node: Node 

77 outcome: OperationOutcome 

78 detail: object = None 

79 

80 

81@dataclass(frozen=True) 

82class Interruption: 

83 """Result of the built-in Abort attempt for a dropped call. 

84 

85 Acknowledged means the device answered, not that motion stopped. 

86 Unsupported means nothing was sent. `error` holds the Abort exception 

87 when available. 

88 """ 

89 

90 outcome: InterruptionOutcome 

91 error: BaseException | None = None 

92 

93 

94class Dispatcher: 

95 """Send operations using one run's header sources. 

96 

97 The bound sensor, clients and observer may be shared across runs; construct 

98 a dispatcher per run to keep base and sampled contexts separate. 

99 """ 

100 

101 def __init__( 

102 self, 

103 sensor: BoundSensor, 

104 clients: Mapping[str, DeviceClient], 

105 *, 

106 contexts: DeviceContexts | None = None, 

107 instrument_contexts: InstrumentContexts | None = None, 

108 base: sk.Context | None = None, 

109 events: AsyncObserver[OperationEvent] | None = None, 

110 ): 

111 self.sensor = sensor 

112 self.clients = clients 

113 self.contexts = contexts 

114 self.instrument_contexts = instrument_contexts 

115 self.base = base 

116 self.events = events 

117 

118 async def perform( 

119 self, 

120 operation: Operation, 

121 node: Node, 

122 attempt: AttemptRecorder, 

123 interrupted: InterruptionRecorder, 

124 ) -> object: 

125 """Send an operation under its resolved timeout and drain its call 

126 task. 

127 

128 Record the attempt before sending. A dropped call triggers Abort; its 

129 outcome goes to `interrupted` without replacing the operation's 

130 failure. Held caller cancellation takes precedence over a timeout after 

131 local teardown completes. 

132 

133 Args: 

134 operation: Planned command, target and timeout. 

135 node: Graph node included in operation events. 

136 attempt: Callback recording that dispatch is starting. 

137 interrupted: Callback storing the Abort outcome, including when 

138 the device does not support Abort. 

139 

140 Returns: 

141 The device command's result. 

142 

143 Raises: 

144 TimeoutError: The command exceeds its timeout or the transport 

145 times out. 

146 LookupError: No client exists for the target; nothing is sent. 

147 asyncio.CancelledError: Cancellation propagates after local tasks 

148 drain. 

149 Exception: A command or header-building error propagates. 

150 """ 

151 device = operation.target.device 

152 client = self.clients.get(device) 

153 

154 if client is None: 

155 raise LookupError(f"no client for device '{device}'") 

156 

157 command = self.outgoing(operation) 

158 

159 async def send() -> object: 

160 return await client.command(command) 

161 

162 attempt(operation) 

163 self.notify(OperationEvent(operation, node, "begin")) 

164 sending = asyncio.create_task(send()) 

165 expired, cancelled = await _owned(sending, operation.timeout_s, interruptible=True) 

166 

167 # Handle Abort outside the command wait to avoid recursive interruption. 

168 if _dropped(sending): 

169 try: 

170 await self.abort(device, interrupted) 

171 except asyncio.CancelledError as e: 

172 cancelled = cancelled or e 

173 

174 return self._concluded(operation, node, sending, expired, cancelled) 

175 

176 def outgoing(self, operation: Operation) -> DeviceCommand: 

177 """Return the command to send, adding a fresh header for an 

178 acquisition. 

179 

180 Acquisition commands are deep-copied; ordinary commands are returned 

181 unchanged. 

182 """ 

183 if operation.acquisition is None: 

184 return operation.command 

185 

186 # Give each acquisition its own context without modifying the planned command. 

187 return operation.command.model_copy(deep=True, update={"context": self.header(operation)}) 

188 

189 def header(self, operation: Operation) -> sk.Context: 

190 """Merge task, instrument, and device context for a capture. 

191 

192 Base context and planned frame keywords form the task context. 

193 Device snapshots merge from root to capture target. Later values 

194 replace earlier values. 

195 

196 Raises: 

197 KeyError: The target is not an instrument or has no registered context. 

198 """ 

199 # Frame numbering is already included in planned acquisition keywords. 

200 planned = operation.acquisition.keywords if operation.acquisition is not None else None 

201 instrument = ( 

202 self.instrument_contexts(operation.target) 

203 if self.instrument_contexts is not None 

204 else None 

205 ) 

206 reported = self.contexts() if self.contexts is not None else {} 

207 chain = self.sensor.topology.chain(operation.target) 

208 

209 return merge_contexts( 

210 self.base, planned, instrument, *(reported.get(p.device) for p in chain) 

211 ) 

212 

213 async def abort(self, device: str, record: InterruptionRecorder) -> Interruption: 

214 """Attempt built-in Abort once, recording the outcome before 

215 returning or raising. 

216 

217 Unsupported devices receive nothing. Failures become interruption 

218 results; no fallback command or recursive Abort is sent. Wait up to 

219 `ABORT_TIMEOUT_S` for a response, then drain local teardown. Hold 

220 caller cancellation until the attempt ends. 

221 

222 Args: 

223 device: Target of the interrupted call. 

224 record: Callback storing the interruption result. 

225 

226 Returns: 

227 The interruption result also passed to `record`. 

228 

229 Raises: 

230 asyncio.CancelledError: The caller was cancelled during the 

231 attempt. 

232 """ 

233 if Abort.model_tag() not in self.sensor.supported_commands(device): 

234 logger.warning(f"{device}: interrupted, and it has no Abort") 

235 record(interruption := Interruption("unsupported")) 

236 return interruption 

237 

238 async def abort() -> object: 

239 return await self.clients[device].command(Abort()) 

240 

241 # Send directly so Abort failure cannot trigger another Abort. 

242 attempt = asyncio.create_task(abort()) 

243 expired, cancelled = await _owned(attempt, ABORT_TIMEOUT_S, interruptible=False) 

244 

245 if expired: 

246 interruption = Interruption("timed_out") 

247 logger.warning(f"{device}: Abort unanswered after {ABORT_TIMEOUT_S}s") 

248 elif attempt.cancelled(): 

249 # An unexpired attempt was cancelled externally, such as by loop teardown. 

250 interruption = Interruption("failed") 

251 logger.warning(f"{device}: Abort cancelled") 

252 elif (error := attempt.exception()) is not None: 

253 interruption = Interruption("failed", error) 

254 logger.warning(f"{device}: Abort failed ({error})") 

255 else: 

256 interruption = Interruption("acknowledged") 

257 logger.info(f"{device}: Abort acknowledged") 

258 

259 # Preserve held cancellation even if recording fails. 

260 try: 

261 record(interruption) 

262 finally: 

263 if cancelled is not None: 

264 raise cancelled 

265 

266 return interruption 

267 

268 def notify(self, event: OperationEvent) -> None: 

269 """Log an operation event and notify observers without waiting on 

270 subscribers. 

271 

272 Observer failures are logged rather than propagated into dispatch. 

273 """ 

274 where = f"{event.operation.id}: {event.node.label.strip()}" 

275 

276 match event.outcome: 

277 case "begin": 

278 logger.info(where) 

279 case "ok": 

280 logger.debug(f"{where}: done") 

281 case "failed": 

282 logger.warning(f"{where}: failed ({event.detail})") 

283 case "cancelled": 

284 logger.warning(f"{where}: cancelled") 

285 

286 if self.events is None: 

287 return 

288 

289 try: 

290 self.events.notify(event) 

291 except Exception as e: 

292 logger.warning(f"{where}: an operation subscriber failed ({e!r})") 

293 

294 def _concluded( 

295 self, 

296 operation: Operation, 

297 node: Node, 

298 sending: asyncio.Task, 

299 expired: bool, 

300 cancelled: asyncio.CancelledError | None, 

301 ) -> object: 

302 """Emit the call's terminal event, then return its result or 

303 propagate failure. 

304 

305 A held caller cancellation takes precedence even if the call ended 

306 otherwise. 

307 """ 

308 match sending.cancelled(), expired: 

309 case True, True if cancelled is None: 

310 error: BaseException | None = TimeoutError( 

311 f"'{operation.id}' did not finish within {operation.timeout_s}s" 

312 ) 

313 case True, _: 

314 error = cancelled or asyncio.CancelledError() 

315 case _: 

316 error = sending.exception() 

317 

318 match error: 

319 case None: 

320 self.notify(OperationEvent(operation, node, "ok", sending.result())) 

321 case asyncio.CancelledError(): 

322 self.notify(OperationEvent(operation, node, "cancelled")) 

323 case _: 

324 self.notify(OperationEvent(operation, node, "failed", error)) 

325 

326 if cancelled is not None: 

327 raise cancelled 

328 

329 if error is not None: 

330 raise error 

331 

332 return sending.result() 

333 

334 

335async def _owned( 

336 task: asyncio.Task, seconds: float | None, *, interruptible: bool 

337) -> tuple[bool, asyncio.CancelledError | None]: 

338 """Wait for an owned task, cancelling it once when the initial wait 

339 ends. 

340 

341 For interruptible tasks, caller cancellation ends the initial wait. 

342 Otherwise wait until completion or timeout. Drain afterward without a 

343 separate timeout, retaining the first caller cancellation and its 

344 cancellation count. 

345 

346 Returns: 

347 Whether the task expired and the first caller cancellation, if any. 

348 """ 

349 expired, cancelled = await _until_stopped(task, seconds, interruptible) 

350 task.cancel() 

351 

352 while not task.done(): 

353 try: 

354 await asyncio.wait({task}) 

355 except asyncio.CancelledError as e: 

356 cancelled = cancelled or e 

357 

358 return expired, cancelled 

359 

360 

361async def _until_stopped( 

362 task: asyncio.Task, seconds: float | None, interruptible: bool 

363) -> tuple[bool, asyncio.CancelledError | None]: 

364 """Wait for completion, timeout or caller cancellation when 

365 interruptible. 

366 

367 Returns: 

368 Whether the task expired and the first caller cancellation, if any. 

369 """ 

370 loop = asyncio.get_running_loop() 

371 expiry = None if seconds is None else loop.time() + seconds 

372 cancelled: asyncio.CancelledError | None = None 

373 

374 while not task.done(): 

375 remaining = None if expiry is None else expiry - loop.time() 

376 

377 try: 

378 await asyncio.wait({task}, timeout=remaining) 

379 except asyncio.CancelledError as e: 

380 cancelled = cancelled or e 

381 

382 if interruptible: 

383 break 

384 

385 continue 

386 

387 if not task.done(): 

388 return True, cancelled 

389 

390 return False, cancelled 

391 

392 

393def _dropped(sending: asyncio.Task) -> bool: 

394 """Test whether the local call was cancelled or ended with a timeout. 

395 

396 A transport timeout can leave work running on the device. 

397 """ 

398 return sending.cancelled() or isinstance(sending.exception(), TimeoutError)