Coverage for core / src / sensorkit / core / controller.py: 96%

326 statements  

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

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import asyncio 

5import contextlib 

6import math 

7from abc import abstractmethod 

8from collections.abc import AsyncIterator, Coroutine, Iterator 

9from dataclasses import dataclass 

10from datetime import UTC, datetime 

11from enum import StrEnum, auto 

12from typing import ( 

13 TYPE_CHECKING, 

14 Any, 

15 Callable, 

16 ClassVar, 

17 Collection, 

18 Literal, 

19 Mapping, 

20 NoReturn, 

21 Self, 

22 overload, 

23) 

24 

25import uuid_utils.compat as uuid 

26from pydantic import BaseModel, Field, model_validator 

27 

28from sensorkit.backend.event import Event 

29from sensorkit.backend.request import Call, declare_long_request, declare_request 

30from sensorkit.common.aio import AsyncObserver, OverflowPolicy, defer_cancellation 

31from sensorkit.common.keyword import KeywordDict 

32from sensorkit.core.device import DeviceClient 

33from sensorkit.core.entity import ControllerDetails, EntityClient, EntityInterface, EntityRef 

34from sensorkit.core.state import EventSourcedState 

35from sensorkit.core.task import Task, TaskExecution 

36from sensorkit.data.context import Context, ContextSubscription 

37 

38if TYPE_CHECKING: 

39 from sensorkit.core.client import SensorKit 

40 

41 

42class InternalControllerState(StrEnum): 

43 """High-level Controller states.""" 

44 OPERATE = auto() 

45 STANDBY = auto() 

46 SHUTDOWN = auto() 

47 ERROR = auto() 

48 """A known failure prevents asserting an achieved lifecycle state.""" 

49 UNKNOWN = auto() 

50 """No achieved operating state is established.""" 

51 TRANSITION = auto() 

52 """A lifecycle task is changing the controller's operating state.""" 

53 

54 

55type KnownControllerState = Literal[ 

56 InternalControllerState.OPERATE, 

57 InternalControllerState.STANDBY, 

58 InternalControllerState.SHUTDOWN, 

59] 

60"""An achieved operating state, reported with its lifecycle input.""" 

61 

62type LatchedControllerState = Literal[ 

63 InternalControllerState.UNKNOWN, 

64 InternalControllerState.ERROR, 

65] 

66"""A state held until a lifecycle task succeeds.""" 

67 

68 

69class ControllerEnableState(Event): 

70 """Event indicating the Controller enable state has changed.""" 

71 enabled: bool 

72 

73 

74class TaskFinishInfo(BaseModel): 

75 """Metadata recorded when a task completes, including whether it was aborted or raised an error.""" 

76 

77 timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC)) 

78 aborted: bool = False 

79 error: bool | str = False 

80 

81 

82class TaskExecutionState(Event): 

83 """Event representing the current task execution status of a Controller.""" 

84 

85 executing: bool = False 

86 aborting: bool = False 

87 finished: TaskFinishInfo | None = None 

88 execution: TaskExecution | None 

89 context: dict | None = None 

90 

91 @model_validator(mode="before") 

92 @classmethod 

93 def _migrate_legacy_task(cls, data: Any) -> Any: 

94 """Upgrade events persisted by versions predating the Task/TaskExecution split. 

95 

96 Two legacy shapes are upgraded here: 

97 

98 * Versions before the split stored the executing task on `task` as a flat 

99 `ControllerTask` — identity (`task_id`, `controller_id`), `context` and the 

100 `end_time` deadline embedded alongside the discriminated task fields. This version 

101 expects a `TaskExecution` envelope wrapping the semantic `task`. 

102 * Versions after the split but before `task` was renamed to `execution` stored the 

103 envelope under the `task` key. 

104 

105 Both are carried onto `execution`. Rewriting the legacy shape here covers both reads: 

106 the KV `ControllerState` snapshot (whose `execution_state` is validated as this model) 

107 and event-stream replay (where each event is validated through the registry). Without it, 

108 state carried by a NATS broker from an older version would raise a `ValidationError`. 

109 """ 

110 if not isinstance(data, dict): 

111 return data 

112 

113 # The pre-rename wire format carried the executing task (flat or enveloped) under `task`. 

114 # Lift it onto `execution` so the rest of the migration — and the model — see one key. 

115 if "execution" not in data and "task" in data: 

116 data = dict(data) 

117 data["execution"] = data.pop("task") 

118 

119 legacy = data.get("execution") 

120 

121 # A legacy task is a flat `ControllerTask`: it carries the discriminator at the top level 

122 # and has no nested `task` envelope. A current `TaskExecution` always nests `task`. 

123 if not isinstance(legacy, dict) or "task_type" not in legacy or "task" in legacy: 

124 return data 

125 

126 # Lift the envelope fields off the task; the remaining keys (`task_type` plus domain 

127 # fields) become the wrapped semantic task. The legacy `end_time` was the execution 

128 # deadline, so it maps to the envelope's `expiry_time`; task types that still declare 

129 # `end_time` as a domain field (e.g. `standard_collect`) keep their own copy because it 

130 # is left in the wrapped task. 

131 envelope = { 

132 "task": { 

133 k: v for k, v in legacy.items() if k not in ("task_id", "controller_id", "context") 

134 }, 

135 "task_id": legacy.get("task_id"), 

136 "controller_id": legacy.get("controller_id"), 

137 "context": legacy.get("context"), 

138 "expiry_time": legacy.get("end_time"), 

139 } 

140 

141 return {**data, "execution": envelope} 

142 

143 @model_validator(mode="after") 

144 def _validate(self): 

145 if self.executing and self.execution is None: 

146 raise ValueError("inconsistent state fields: executing with no task") 

147 

148 if self.aborting and not self.executing: 

149 raise ValueError("inconsistent state fields: aborting but not executing") 

150 

151 if self.finished is not None and (self.executing or self.aborting): 

152 raise ValueError("inconsistent state fields: finished but executing or aborting") 

153 

154 return self 

155 

156 

157class ControllerOperatingState(Event): 

158 """Reported operating state and lifecycle input. 

159 

160 Achieved states require explicit context, including an empty mapping. 

161 Missing or null context changes an achieved state to UNKNOWN. 

162 """ 

163 current: InternalControllerState 

164 previous: InternalControllerState | None = None 

165 target: InternalControllerState | None = None 

166 context: KeywordDict = Field(default_factory=KeywordDict) 

167 """Lifecycle input for the current or most recent attempt. 

168 

169 For an achieved state, this is the input the controller reported with it. If the 

170 controller reports no known states, it is the input of the lifecycle task that 

171 established the state. Other states retain the input for diagnosis. 

172 """ 

173 

174 NO_CHANGE: ClassVar[object] = object() 

175 

176 @model_validator(mode="before") 

177 @classmethod 

178 def _migrate_legacy_context(cls, data: Any) -> Any: 

179 """Normalize lifecycle records with missing or null context.""" 

180 if not isinstance(data, dict) or data.get("context") is not None: 

181 return data 

182 

183 # Keep missing context detectable during startup normalization. 

184 data = {key: value for key, value in data.items() if key != "context"} 

185 

186 match data.get("current"): 

187 case ( 

188 InternalControllerState.OPERATE 

189 | InternalControllerState.STANDBY 

190 | InternalControllerState.SHUTDOWN 

191 ): 

192 return { 

193 **data, 

194 "current": InternalControllerState.UNKNOWN, 

195 "previous": data["current"], 

196 } 

197 

198 return data 

199 

200 def matches( 

201 self, 

202 state: InternalControllerState, 

203 context: KeywordDict, 

204 ) -> bool: 

205 """Return whether the reported state and context match with no transition pending.""" 

206 return self.current == state and self.target is None and self.context == context 

207 

208 def derive( 

209 self, 

210 *, 

211 current: InternalControllerState = NO_CHANGE, 

212 target: InternalControllerState | None = NO_CHANGE, 

213 context: KeywordDict = NO_CHANGE, 

214 ) -> Self: 

215 """Return a new ControllerOperatingState based on this one, updating only the specified fields.""" 

216 if current == self.current: 

217 # This ensures `previous` isn't unnecessarily rotated out. 

218 current = self.NO_CHANGE 

219 

220 return ControllerOperatingState( 

221 current=self.current if current == self.NO_CHANGE else current, 

222 previous=self.previous if current == self.NO_CHANGE else self.current, 

223 target=self.target if target == self.NO_CHANGE else target, 

224 context=self.context if context is self.NO_CHANGE else context, 

225 ) 

226 

227 

228class ControllerState(EventSourcedState): 

229 """Controller state.""" 

230 enable_state: ControllerEnableState 

231 operating_state: ControllerOperatingState 

232 execution_state: TaskExecutionState 

233 

234 

235class ControllerEnableStateRequest(BaseModel): 

236 """Request that a Controller enable or disable its task handlers.""" 

237 enable: bool 

238 

239 

240set_enable_state_request = declare_request( 

241 "set_enable_state", 

242 message=ControllerEnableStateRequest, 

243) 

244"""Set the enable state of a Controller.""" 

245 

246 

247class ExecuteRequestMessage(BaseModel): 

248 """A task execution request. 

249 

250 The client supplies the semantic `task` plus optional execution parameters. The controller 

251 mints the identity (`task_id`, `controller_id`) and returns the resulting `TaskExecution` in 

252 the response. 

253 """ 

254 task: Task 

255 context: KeywordDict | None = None 

256 expiry_time: datetime | None = None 

257 interrupt: bool = False 

258 

259 

260class ExecuteResponseMessage(BaseModel): 

261 """A response to a task execution request. 

262 

263 Carries the minted `TaskExecution` envelope so the client learns the assigned `task_id` (e.g. 

264 for a subsequent abort) without having to supply it. 

265 """ 

266 execution: TaskExecution | None = None 

267 

268 

269class AbortRequestMessage(BaseModel): 

270 """A Task abort request.""" 

271 task_id: uuid.UUID | None 

272 """If given, verifies the running task ID matches before aborting.""" 

273 

274 

275class AbortResponseMessage(BaseModel): 

276 """Response to a Task abort request.""" 

277 aborting: bool 

278 """True if the abort is underway, False if the abort was rejected.""" 

279 

280 task_id: uuid.UUID | None 

281 """If the abort was accepted, the task ID of the task being aborted.""" 

282 

283 

284class TaskExecutionResult(BaseModel): 

285 """Result of a successful Task execution.""" 

286 task_id: uuid.UUID 

287 start_time: datetime 

288 end_time: datetime 

289 

290 

291execute_task_request = declare_long_request( 

292 name="execute_task", 

293 message=ExecuteRequestMessage, 

294 response=ExecuteResponseMessage, 

295 result=TaskExecutionResult, 

296) 

297 

298abort_task_request = declare_long_request( 

299 name="abort_task", 

300 message=AbortRequestMessage, 

301 response=AbortResponseMessage, 

302) 

303 

304 

305class ControllerClient(EntityClient): 

306 """Object that exposes client-side functionality of a Controller.""" 

307 

308 async def get_details(self) -> ControllerDetails: 

309 """Fetch the controller's current advertised details. 

310 

311 Raises: 

312 KeyNotFound: The entity has no stored metadata. 

313 ValueError: The metadata has no controller details. 

314 """ 

315 details = await super().get_details() 

316 

317 if not isinstance(details, ControllerDetails): 

318 raise ValueError(f"Entity '{self.entity}' has no controller details") 

319 

320 return details 

321 

322 async def enable(self): 

323 """Enable the controller's task handlers.""" 

324 return await self.call( 

325 set_enable_state_request, 

326 ControllerEnableStateRequest(enable=True) 

327 ) 

328 

329 async def disable(self): 

330 """Disable the controller's task handlers.""" 

331 return await self.call( 

332 set_enable_state_request, 

333 ControllerEnableStateRequest(enable=False) 

334 ) 

335 

336 def execute_task( 

337 self, 

338 task: Task, 

339 *, 

340 context: KeywordDict | None = None, 

341 expiry_time: datetime | None = None, 

342 interrupt=False, 

343 ) -> Call[ExecuteResponseMessage, TaskExecutionResult]: 

344 """Send a task execution request to the controller and return a `Call` tracking completion. 

345 

346 The controller assigns the `task_id` and `controller_id`. The optional execution 

347 parameters are recorded on the resulting `TaskExecution`. 

348 

349 Args: 

350 task: The semantic task to execute. 

351 context: Optional keyword context to attach to the execution. 

352 expiry_time: Optional time after which the execution should be considered expired. 

353 interrupt: Whether to interrupt any task currently in progress. 

354 

355 Returns: 

356 A `Call` that yields the final `TaskExecutionResult` when awaited. 

357 """ 

358 return self.call( 

359 execute_task_request, 

360 ExecuteRequestMessage( 

361 task=task, 

362 context=context, 

363 expiry_time=expiry_time, 

364 interrupt=interrupt, 

365 ), 

366 ) 

367 

368 async def start_task( 

369 self, 

370 task: Task, 

371 *, 

372 context: KeywordDict | None = None, 

373 expiry_time: datetime | None = None, 

374 interrupt=False, 

375 ) -> TaskExecution: 

376 """Submit a task and return its execution envelope once the controller acknowledges it. 

377 

378 Unlike `execute_task`, this awaits only the controller's initial response, then returns the 

379 minted `TaskExecution`. The controller assigns the identity (`task_id`, `controller_id`); 

380 the returned execution is bound to the in-flight call, so the caller can read the assigned 

381 identity immediately and `await` the execution itself for the final `TaskExecutionResult`. 

382 

383 Args: 

384 task: The semantic task to execute. 

385 context: Optional keyword context to attach to the execution. 

386 expiry_time: Optional time after which the execution should be considered expired. 

387 interrupt: Whether to interrupt any task currently in progress. 

388 

389 Returns: 

390 The minted execution envelope, awaitable for the final result. 

391 """ 

392 call = self.execute_task( 

393 task, context=context, expiry_time=expiry_time, interrupt=interrupt 

394 ) 

395 response = await call.invoke() 

396 execution = response.execution 

397 assert execution is not None, "controller acknowledged task without an execution envelope" 

398 

399 # The in-flight call's future resolves to the result in this (client) context. 

400 execution.bind_result(call.get_future()) 

401 

402 return execution 

403 

404 def abort_task(self, task_id: uuid.UUID | None = None) -> Call[AbortResponseMessage, None]: 

405 """Send an abort request to the controller for the optionally specified task ID.""" 

406 return self.call(abort_task_request, AbortRequestMessage(task_id=task_id)) 

407 

408 async def wait_for_task(self, task_id: uuid.UUID | None = None): 

409 """Wait until the controller reports that no task (or the specified task) is executing.""" 

410 # FIXME: This is unreliable at present due to backend limitations. 

411 async for event in ControllerState.event_stream(self, TaskExecutionState): 

412 if task_id is not None: 

413 if event.execution is None or event.execution.task_id != task_id: 

414 return None 

415 

416 if not event.executing: 

417 return event 

418 

419 raise RuntimeError("stream ended unexpectedly") 

420 

421 

422class ExecutionStateStream: 

423 """Stream state events for one execution, including events received before it is known. 

424 

425 The stream buffers a controller's state events from creation. Once bound to an execution, 

426 iteration yields that execution's events in arrival order. After closing, iteration ends once 

427 the buffered events are consumed. Multiple iterators share the buffer. 

428 """ 

429 

430 def __init__(self, controller: ControllerClient): 

431 self.execution: TaskExecution | None = None 

432 """The execution whose state events are yielded.""" 

433 self._subscription = controller.get_event_mux().subscribe(TaskExecutionState) 

434 

435 def bind(self, execution: TaskExecution): 

436 """Select the execution whose state events are yielded. 

437 

438 Raises: 

439 RuntimeError: If the stream is already bound. 

440 """ 

441 if self.execution is not None: 

442 raise RuntimeError("Execution state stream is already bound") 

443 

444 self.execution = execution 

445 

446 def close(self): 

447 """Stop receiving state events, leaving buffered events readable.""" 

448 self._subscription.close() 

449 

450 async def __aiter__(self) -> AsyncIterator[TaskExecutionState]: 

451 """Yield state events for the bound execution. 

452 

453 Raises: 

454 RuntimeError: If no execution is bound. 

455 """ 

456 if self.execution is None: 

457 raise RuntimeError("Execution state stream is not bound") 

458 

459 task_id = self.execution.task_id 

460 

461 async for state in self._subscription: 

462 match state: 

463 case TaskExecutionState(execution=execution) if ( 

464 execution is not None and execution.task_id == task_id 

465 ): 

466 yield state 

467 

468 

469class ControllerRef(EntityRef[ControllerClient]): 

470 """A serializable reference to a controller client.""" 

471 

472 def _get_client(self, kit: SensorKit) -> ControllerClient: 

473 return kit.controller(self.name) 

474 

475 

476class ControllerStateUnknown(Exception): 

477 """Controller state is unavailable because monitoring is not ready or has ended.""" 

478 

479 

480class ControllerMonitor: 

481 """Continuously monitor controller state. 

482 

483 Create another monitor to resume after failure or stop. 

484 A healthy monitor does not prove the controller is online. 

485 """ 

486 

487 def __init__(self, controller: ControllerClient): 

488 self.controller = controller 

489 self._observer: AsyncObserver[ControllerOperatingState] = AsyncObserver() 

490 self._state: ControllerState | None = None 

491 self._lifecycle: ( 

492 tuple[InternalControllerState, InternalControllerState | None, KeywordDict] | None 

493 ) = None 

494 self._error: Exception | None = None 

495 self._reader: asyncio.Task[None] | None = None 

496 self._teardown: asyncio.Task[None] | None = None 

497 

498 # Set by the first state, a failure, or a stop. 

499 self._startup_complete = asyncio.Event() 

500 

501 async def start(self, *, timeout: float = 10.0) -> None: 

502 """Start monitoring controller state and wait for the first valid state. 

503 

504 A state that does not exist yet is awaited until created. 

505 

506 Args: 

507 timeout: Seconds to wait for the first valid state. 

508 

509 Raises: 

510 ValueError: If `timeout` is not positive and finite. 

511 RuntimeError: If the monitor was already started. 

512 TimeoutError: If no valid state arrives in time. 

513 ControllerStateUnknown: If state monitoring fails or stops first. 

514 """ 

515 if not (math.isfinite(timeout) and timeout > 0): 

516 raise ValueError(f"timeout must be positive and finite, got {timeout}") 

517 

518 if self._reader is not None: 

519 raise RuntimeError("A controller monitor can only be started once") 

520 

521 self._reader = asyncio.create_task(self._read()) 

522 

523 try: 

524 async with asyncio.timeout(timeout): 

525 await self._startup_complete.wait() 

526 except TimeoutError: 

527 error = TimeoutError(f"{self.controller.entity} state not received in {timeout} s") 

528 self._fail(error) 

529 await self._abandon(error) 

530 except asyncio.CancelledError as e: 

531 await self._abandon(e) 

532 

533 try: 

534 self._healthy_state() 

535 except ControllerStateUnknown as e: 

536 await self._abandon(e) 

537 

538 async def stop(self) -> None: 

539 """Stop monitoring controller state and wait until its subscription is released. 

540 

541 Repeated calls join the same cleanup. Before the first start, this does nothing. 

542 Subscription cleanup failures propagate to the caller. 

543 """ 

544 if self._reader is not None: 

545 await self._shut_down() 

546 

547 @property 

548 def state(self) -> ControllerState: 

549 """Copy of the latest controller state. 

550 

551 Raises: 

552 ControllerStateUnknown: If state monitoring is not ready, failed, or stopped. 

553 """ 

554 return self._healthy_state().model_copy(deep=True) 

555 

556 def healthy(self) -> bool: 

557 """Whether valid controller state is available and monitoring has not ended. 

558 

559 This does not check whether the controller is online. 

560 """ 

561 return self._state is not None and not self._observer.closed 

562 

563 @property 

564 def operating_state(self) -> ControllerOperatingState: 

565 """Copy of the latest operating state. 

566 

567 Raises: 

568 ControllerStateUnknown: If state monitoring is not ready, failed, or stopped. 

569 """ 

570 return self._healthy_state().operating_state.model_copy(deep=True) 

571 

572 @property 

573 def last_state(self) -> ControllerState | None: 

574 """Copy of the last state received, including after monitoring ends.""" 

575 return None if self._state is None else self._state.model_copy(deep=True) 

576 

577 @property 

578 def error(self) -> Exception | None: 

579 """The first state monitoring failure, retained after shutdown.""" 

580 return self._error 

581 

582 @contextlib.contextmanager 

583 def state_changes( 

584 self, 

585 *, 

586 initial_value: bool = True, 

587 maxsize: int = 64, 

588 overflow: OverflowPolicy = "close", 

589 ) -> Iterator[asyncio.Queue[ControllerOperatingState]]: 

590 """Subscribe to changes of operating state, target, or lifecycle context. 

591 

592 Subscribers share each state update and must not modify it. The queue shuts down 

593 when monitoring fails or stops, or on overflow with the `close` policy. 

594 

595 Args: 

596 initial_value: Whether to queue the current state first. 

597 maxsize: Bound on queued state updates. 

598 overflow: Handling of a full queue. `close` shuts down this queue only. 

599 `drop_oldest` discards its oldest state update. 

600 

601 Yields: 

602 The subscriber queue, unsubscribed on exit. 

603 

604 Raises: 

605 ControllerStateUnknown: If state monitoring is not ready, failed, or stopped. 

606 ValueError: If `maxsize` or `overflow` is invalid. 

607 """ 

608 self._healthy_state() 

609 

610 with self._observer.subscription( 

611 initial_value=initial_value, maxsize=maxsize, overflow=overflow 

612 ) as queue: 

613 yield queue 

614 

615 def _healthy_state(self) -> ControllerState: 

616 """Return the cached state, or raise if the monitor is unhealthy.""" 

617 if self._state is not None and not self._observer.closed: 

618 return self._state 

619 

620 match self._error, self._observer.closed: 

621 case None, False: 

622 reason = "is not ready" 

623 case None, True: 

624 reason = "stopped" 

625 case _: 

626 reason = "failed" 

627 

628 raise ControllerStateUnknown( 

629 f"{self.controller.entity} state is unknown because monitoring {reason}" 

630 ) from self._error 

631 

632 async def _read(self): 

633 states = self.controller.kv_monitor_model(ControllerState, strict=True) 

634 

635 try: 

636 async with contextlib.aclosing(states): 

637 async for state in states: 

638 self._receive(state) 

639 

640 raise RuntimeError(f"{self.controller.entity} state stream ended") 

641 except asyncio.CancelledError as e: 

642 if self._teardown is None: 

643 failure = RuntimeError(f"{self.controller.entity} state monitoring canceled") 

644 failure.__cause__ = e 

645 self._fail(failure) 

646 

647 raise 

648 except Exception as e: 

649 # Cleanup failures after a stop belong to the stopping caller. 

650 if self._teardown is not None: 

651 raise 

652 

653 self._fail(e) 

654 

655 def _receive(self, state: ControllerState): 

656 operating = state.operating_state 

657 lifecycle = (operating.current, operating.target, operating.context) 

658 self._state = state 

659 

660 if lifecycle != self._lifecycle: 

661 self._lifecycle = lifecycle 

662 

663 # Subscribers share this copy, apart from the cache. 

664 self._observer.notify(operating.model_copy(deep=True)) 

665 

666 self._startup_complete.set() 

667 

668 def _fail(self, error: Exception): 

669 """Record the first failure and stop monitoring controller state.""" 

670 if self._error is None: 

671 self._error = error 

672 

673 self._observer.close() 

674 self._startup_complete.set() 

675 

676 async def _abandon(self, failure: BaseException) -> NoReturn: 

677 """Join teardown after a failed start, then raise the startup failure.""" 

678 # A later stop can report cleanup failure without replacing the startup failure. 

679 with contextlib.suppress(Exception): 

680 await self._shut_down() 

681 

682 raise failure 

683 

684 async def _shut_down(self): 

685 await defer_cancellation(self._request_teardown()) 

686 

687 def _request_teardown(self) -> asyncio.Task[None]: 

688 if self._teardown is None: 

689 # No await before cancellation, so the reader cannot deliver after closure. 

690 self._observer.close() 

691 self._startup_complete.set() 

692 self._reader.cancel() 

693 self._teardown = asyncio.create_task(self._join_reader(self._reader)) 

694 

695 return self._teardown 

696 

697 @staticmethod 

698 async def _join_reader(reader: asyncio.Task[None]): 

699 # The reader's own cancellation is expected and does not propagate. 

700 await asyncio.wait((reader,)) 

701 

702 if not reader.cancelled(): 

703 reader.result() 

704 

705 

706@dataclass 

707class ControllerDevice(Mapping[Any, Any]): 

708 """A device attached to a controller, providing cached keyword access via its ContextSubscription.""" 

709 

710 client: DeviceClient 

711 subscription: ContextSubscription 

712 

713 def __getitem__(self, key, /): 

714 return self.subscription.cache[key] 

715 

716 def __len__(self): 

717 return len(self.subscription.cache) 

718 

719 def __iter__(self): 

720 return iter(self.subscription.cache) 

721 

722 

723type TaskHandlerCallback[T: Task] = Callable[[T], Coroutine[Any, Any, None]] 

724"""A task handler receiving its task.""" 

725 

726type ExecutionHandlerCallback[T: Task] = Callable[[TaskExecution[T]], Coroutine[Any, Any, None]] 

727"""A task handler receiving its task's execution envelope.""" 

728 

729 

730class ControllerInterface(EntityInterface): 

731 """Interface describing an implementation of a controller.""" 

732 

733 @abstractmethod 

734 def on_enable(self, func: Callable[[], None]): 

735 """Register a callback to invoke when the controller is enabled.""" 

736 ... 

737 

738 @abstractmethod 

739 def on_disable(self, func: Callable[[], None]): 

740 """Register a callback to invoke when the controller is disabled.""" 

741 ... 

742 

743 @abstractmethod 

744 def register_instrument( 

745 self, 

746 name: str, 

747 *, 

748 devices: Collection[str | DeviceClient] = (), 

749 ) -> None: 

750 """Register instrument metadata for discovery and capture context. 

751 

752 Register during attachment for automatic publication. Later additions 

753 require `publish_entity_info()`. Call `use_device()` separately for 

754 device dependencies. 

755 

756 Args: 

757 name: Case-sensitive instrument name, unique within this controller. 

758 devices: Associated device IDs or clients. Clients are stored by 

759 entity ID. Empty and shared associations are allowed. 

760 

761 Raises: 

762 ValueError: The name is empty or duplicates a registered name. 

763 TypeError: A string was supplied instead of a collection of devices. 

764 """ 

765 ... 

766 

767 @abstractmethod 

768 def instrument_context(self, name: str) -> Context: 

769 """Return a fresh context for a registered instrument. 

770 

771 The `Instrument` keyword contains its registered `InstrumentInfo`. 

772 Changing the returned context or metadata leaves the registration unchanged. 

773 

774 Raises: 

775 KeyError: No instrument with this name is registered. 

776 """ 

777 ... 

778 

779 @abstractmethod 

780 def use_device(self, name: str, *, subscribe: list[type] | None = None): 

781 """Declare a device dependency, optionally subscribing to the listed keyword types.""" 

782 ... 

783 

784 @abstractmethod 

785 def get_device(self, name: str) -> ControllerDevice: 

786 """Return the attached ControllerDevice for the given name.""" 

787 ... 

788 

789 @abstractmethod 

790 def all_devices(self) -> Collection[ControllerDevice]: 

791 """Return all attached ControllerDevice objects.""" 

792 ... 

793 

794 @abstractmethod 

795 async def start_device_subscriptions(self): 

796 """Start keyword subscriptions for all declared devices.""" 

797 ... 

798 

799 @abstractmethod 

800 async def stop_device_subscriptions(self): 

801 """Stop keyword subscriptions for all declared devices.""" 

802 ... 

803 

804 @abstractmethod 

805 async def update_context( 

806 self, 

807 *args, 

808 **kwargs, 

809 ) -> Context: 

810 """Update the context of the currently executing task.""" 

811 ... 

812 

813 @abstractmethod 

814 def add_task_handler[T: Task]( 

815 self, 

816 task_model: type[T], 

817 *, 

818 task_callback: TaskHandlerCallback[T] | None = None, 

819 execution_callback: ExecutionHandlerCallback[T] | None = None, 

820 ) -> None: 

821 """Register the handler for a task type. 

822 

823 Supply exactly one callback. 

824 A task callback receives the task. 

825 An execution callback receives the task's execution envelope. 

826 

827 Raises: 

828 TypeError: If neither or both callbacks are supplied. 

829 RuntimeError: If the task type already has a handler. 

830 """ 

831 ... 

832 

833 @abstractmethod 

834 def task_handler(self, task_type: type[Task]) -> Callable[..., TaskHandlerCallback]: 

835 """Return a decorator for a handler that receives the task.""" 

836 ... 

837 

838 @abstractmethod 

839 def task_running(self) -> bool: 

840 """Return True if a task is currently executing on this controller.""" 

841 ... 

842 

843 @overload 

844 async def report_state(self, state: KnownControllerState, context: KeywordDict): ... 

845 

846 @overload 

847 async def report_state(self, state: LatchedControllerState): ... 

848 

849 @abstractmethod 

850 async def report_state( 

851 self, 

852 state: InternalControllerState, 

853 context: KeywordDict | None = None, 

854 ): 

855 """Report the observed controller state and its lifecycle input. 

856 

857 Report a known state only if its lifecycle input can be reconstructed. Each input 

858 keyword must be read back from the hardware or be authoritative in software. 

859 Otherwise, report a known state only if it has no lifecycle input options, or 

860 report no known states. A controller can also report UNKNOWN at startup. 

861 

862 UNKNOWN and ERROR latch until a lifecycle task succeeds and keep the recorded input. 

863 Reporting them while a lifecycle task handler runs does not change how the task 

864 settles. 

865 

866 Reporting a known state replaces the state established by lifecycle task results. 

867 From then on, a lifecycle task succeeds only once its handler returns successfully 

868 and the observed state and input match its target and submitted context. 

869 Reporting UNKNOWN or ERROR after the handler returns and before settlement 

870 fails the task. 

871 A known state reported while latched takes effect when the latch clears. 

872 

873 While a lifecycle task is pending or running, the controller publishes TRANSITION. 

874 

875 Args: 

876 state: The observed state. 

877 context: Lifecycle input of a known state. Omit it for UNKNOWN or ERROR. 

878 

879 Raises: 

880 ValueError: If TRANSITION is requested, a known state omits its input, or 

881 UNKNOWN or ERROR includes input. 

882 """ 

883 ...