Coverage for core / src / sensorkit / core / impl / controller.py: 99%
514 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
2from __future__ import annotations
4import asyncio
5import contextlib
6import copy
7from _contextvars import ContextVar
8from collections.abc import Coroutine, Iterator
9from dataclasses import dataclass, field
10from datetime import UTC, datetime
11from enum import StrEnum, auto
12from typing import (
13 Any,
14 Callable,
15 ClassVar,
16 Collection,
17 Mapping,
18 NamedTuple,
19 overload,
20 override,
21)
23import uuid_utils.compat as uuid
24from loguru import logger
26from sensorkit.backend.base import Entity
27from sensorkit.backend.event import Event
28from sensorkit.backend.request import CallContext
29from sensorkit.common.aio import defer_cancellation
30from sensorkit.common.keyword import KeywordDict
31from sensorkit.core.controller import (
32 AbortRequestMessage,
33 AbortResponseMessage,
34 ControllerDevice,
35 ControllerEnableState,
36 ControllerEnableStateRequest,
37 ControllerInterface,
38 ControllerOperatingState,
39 ControllerState,
40 ExecuteRequestMessage,
41 ExecuteResponseMessage,
42 ExecutionHandlerCallback,
43 InternalControllerState,
44 KnownControllerState,
45 LatchedControllerState,
46 TaskExecutionResult,
47 TaskExecutionState,
48 TaskFinishInfo,
49 TaskHandlerCallback,
50 abort_task_request,
51 execute_task_request,
52 set_enable_state_request,
53)
54from sensorkit.core.device import DeviceClient
55from sensorkit.core.entity import ControllerDetails, EntityInfo, InstrumentInfo
56from sensorkit.core.impl.entity import EntityImpl
57from sensorkit.core.state import StateUpdate
58from sensorkit.core.task import RecoverTask, Task, TaskExecution, TaskInfo
59from sensorkit.data.context import Context, ContextSubscription
62class ControllerDeviceMap(Mapping[str, ControllerDevice]):
63 """Ordered mapping of device names to their ControllerDevice instances, created on demand."""
65 def __init__(self):
66 self._dict: dict[str, ControllerDevice] = {}
68 def get_or_add(self, name: str, *, get_client_func: Callable[[str], DeviceClient]):
69 """Return the ControllerDevice for the given name, creating it if it does not yet exist."""
70 if name not in self._dict:
71 client = get_client_func(name)
72 self._dict[name] = ControllerDevice(client, ContextSubscription(client))
74 return self._dict[name]
76 def __getitem__(self, key, /):
77 return self._dict[key]
79 def __len__(self):
80 return len(self._dict)
82 def __iter__(self):
83 return iter(self._dict)
86class StateWithInput(NamedTuple):
87 """An operating state paired with its lifecycle input."""
89 state: InternalControllerState
90 context: KeywordDict
93class ControllerStateResolver:
94 """Select a controller's settled state from task results, observed states, and a latch.
96 Until a known state is reported, a successful lifecycle task establishes its target
97 and input. Afterward, observed states and their input take precedence over task
98 results. An UNKNOWN or ERROR latch takes precedence over both until a lifecycle task
99 succeeds.
100 """
102 def __init__(self, context: KeywordDict | None = None, *, latched: bool = False):
103 context = context or KeywordDict()
105 self._observed: StateWithInput | None = None
106 self._observed_changed = asyncio.Event()
107 """Set when a report changes the observed state or latches."""
109 self.inferred = InternalControllerState.UNKNOWN
110 """State established by lifecycle task results, used until a known state is reported."""
111 self.commanded = StateWithInput(InternalControllerState.UNKNOWN, context)
112 """Target and input of the most recent successful lifecycle task.
114 Starts as UNKNOWN with the recorded lifecycle input.
115 """
116 self.latch = StateWithInput(InternalControllerState.UNKNOWN, context) if latched else None
117 """UNKNOWN or ERROR held until a lifecycle task succeeds."""
119 @property
120 def observed(self) -> StateWithInput | None:
121 """The latest observed known state and input, or None if no known state was reported."""
122 return self._observed
124 @property
125 def settled(self) -> StateWithInput:
126 """The state to publish while no lifecycle task is pending or running."""
127 if self.latch is not None:
128 return self.latch
130 if self._observed is not None:
131 return self._observed
133 return StateWithInput(self.inferred, self.commanded.context)
135 def record_observed(self, state: InternalControllerState, context: KeywordDict | None):
136 """Apply a state reported by the controller.
138 UNKNOWN and ERROR latch with the settled input. Other states replace the observed
139 state and input.
140 """
141 match state, context:
142 case InternalControllerState.UNKNOWN | InternalControllerState.ERROR, _:
143 self.latch = StateWithInput(state, self.settled.context)
144 case _, KeywordDict() as reported if (state, reported) != self._observed:
145 self._observed = StateWithInput(state, reported)
146 case _:
147 return
149 # Wake current waiters. Later waiters wait for the next change.
150 self._observed_changed.set()
151 self._observed_changed = asyncio.Event()
153 def record_success(self, target: InternalControllerState | None, context: KeywordDict):
154 """Apply a successful lifecycle task, with no target for recovery."""
155 self.latch = None
157 if target is None:
158 self.inferred = InternalControllerState.UNKNOWN
159 else:
160 self.inferred = target
161 self.commanded = StateWithInput(target, context)
163 def record_finish(self, run: TaskRun):
164 """Apply a finished lifecycle task.
166 Success clears the latch. An abort after the task began latches UNKNOWN, and a
167 failure latches ERROR.
168 Recovery retains the settled lifecycle input.
169 """
170 target = run.execution.task.target_state()
171 context = run.submitted_context if target is not None else self.settled.context
173 match run.finish_info:
174 # A task that never began leaves the hardware and the latch as they were.
175 case TaskFinishInfo(error=False, aborted=True) if run.start_time is None:
176 pass
177 case TaskFinishInfo(error=False, aborted=False):
178 self.record_success(target, context)
179 case TaskFinishInfo(error=False):
180 self.latch = StateWithInput(InternalControllerState.UNKNOWN, context)
181 case _:
182 self.latch = StateWithInput(InternalControllerState.ERROR, context)
184 def confirms(self, target: StateWithInput) -> bool:
185 """Return whether no known state was reported or the latest one is the target."""
186 return self._observed is None or self._observed == target
188 async def wait_until_observed(self, target: StateWithInput):
189 """Wait until the observed state and input are the target.
191 Raises:
192 RuntimeError: If UNKNOWN or ERROR is reported while waiting.
193 """
194 latch = self.latch
196 while self._observed != target:
197 await self._observed_changed.wait()
199 # Each latching report records a new latch.
200 if self.latch is not None and self.latch is not latch:
201 raise RuntimeError(f"Controller reported {self.latch.state} before {target.state}")
204class TaskRunPhase(StrEnum):
205 """Progress of a task run.
207 A run is received until its runner first steps. It is interrupting while stopping its
208 predecessor, executing through handler completion and state confirmation, and finished
209 during settlement publication.
210 """
212 RECEIVED = auto()
213 INTERRUPTING = auto()
214 EXECUTING = auto()
215 FINISHED = auto()
218@dataclass(eq=False)
219class TaskRun:
220 """Own a task's runner and execution outcome."""
222 execution: TaskExecution
223 submitted_context: KeywordDict
224 """Framework copy of submitted context, independent of the handler-visible copies."""
226 phase: TaskRunPhase = field(default=TaskRunPhase.RECEIVED, init=False)
227 cancel_requested: bool = field(default=False, init=False)
228 handler_latched_state: StateWithInput | None = field(default=None, init=False)
229 """Controller's latched state when the handler returns successfully.
231 Reporting UNKNOWN or ERROR after the handler returns and before settlement fails the task.
232 """
234 finish_info: TaskFinishInfo = field(
235 default_factory=lambda: TaskFinishInfo(aborted=True),
236 init=False,
237 )
238 start_time: datetime | None = field(default=None, init=False)
240 _handler: ExecutionHandlerCallback[Any] | None = field(default=None, init=False)
241 _runner: asyncio.Task[TaskExecutionResult] | None = field(default=None, init=False)
243 @classmethod
244 def create(
245 cls,
246 controller_id: str,
247 task: Task,
248 *,
249 context: KeywordDict | None,
250 expiry_time: datetime | None,
251 ) -> TaskRun:
252 """Mint execution metadata without scheduling a runner."""
253 execution = TaskExecution(
254 task=task,
255 task_id=uuid.uuid7(),
256 controller_id=controller_id,
257 context=context,
258 expiry_time=expiry_time,
259 )
260 submitted = copy.deepcopy(execution.context)
262 # Add task identity to the working context.
263 execution.context.set(
264 TaskInfo(task=task, id=execution.task_id, controller_id=controller_id)
265 )
267 return cls(execution, submitted)
269 @property
270 def lifecycle(self) -> bool:
271 """Whether the task changes the controller's operating state."""
272 task = self.execution.task
273 return task.target_state() is not None or isinstance(task, RecoverTask)
275 @property
276 def transition(self) -> bool:
277 """Whether lifecycle work is pending, executing, or awaiting confirmation."""
278 return self.lifecycle and self.phase != TaskRunPhase.FINISHED
280 @property
281 def handler(self) -> ExecutionHandlerCallback[Any]:
282 assert self._handler is not None, "execution is not attached"
283 return self._handler
285 @property
286 def runner(self) -> asyncio.Task[TaskExecutionResult]:
287 assert self._runner is not None, "execution is not attached"
288 return self._runner
290 def attach(
291 self,
292 handler: ExecutionHandlerCallback[Any],
293 run: Coroutine[Any, Any, TaskExecutionResult],
294 ):
295 """Bind the handler and schedule the runner of an admitted execution.
297 Raises:
298 RuntimeError: If the execution is already attached.
299 """
300 if self._runner is not None:
301 raise RuntimeError("execution is already attached")
303 self._handler = handler
304 self._runner = asyncio.create_task(run)
306 def done(self) -> bool:
307 return self.runner.done()
309 def cancel(self, msg: str | None = None):
310 """Request cancellation once."""
311 if self.cancel_requested:
312 return
314 self.cancel_requested = True
316 # Canceling before the first step would skip the runner's cleanup.
317 if self.phase != TaskRunPhase.RECEIVED and not self.runner.done():
318 self.runner.cancel(msg)
320 async def join(self):
321 """Join the runner, propagating errors other than execution cancellation."""
322 await asyncio.wait((self.runner,))
324 if not self.runner.cancelled() and (error := self.runner.exception()):
325 raise error
327 async def wait(self):
328 """Join the runner without propagating its outcome.
330 Caller cancellation waits for completion, then propagates.
331 """
332 try:
333 await defer_cancellation(asyncio.wait((self.runner,)))
334 finally:
335 # Observe failures before propagating caller cancellation.
336 if self.runner.done() and not self.runner.cancelled():
337 self.runner.exception()
339 @contextlib.contextmanager
340 def execute(self) -> Iterator[TaskExecution]:
341 """Time execution and record success, failure, or cancellation.
343 Raises:
344 asyncio.CancelledError: If cancellation was requested before execution.
345 """
346 if self.cancel_requested:
347 raise asyncio.CancelledError()
349 self.phase = TaskRunPhase.EXECUTING
350 self.start_time = datetime.now(UTC)
352 try:
353 yield self.execution
354 except Exception as e:
355 self.fail(e)
356 raise
357 else:
358 self.finish_info = TaskFinishInfo()
360 def fail(self, error: Exception):
361 """Record a failure as the execution's finish."""
362 self.finish_info = TaskFinishInfo(error=str(error) or type(error).__name__)
364 def result(self) -> TaskExecutionResult:
365 """Build a successful result with the current time as its end."""
366 assert self.start_time is not None, "execution has not started"
368 return TaskExecutionResult(
369 task_id=self.execution.task_id,
370 start_time=self.start_time,
371 end_time=datetime.now(UTC),
372 )
375class ControllerImpl(EntityImpl, ControllerInterface):
376 """Helper for implementing server-side functionality of a Controller.
378 A controller reports UNKNOWN when its service starts. Attach hooks that can determine the
379 hardware state report it with `report_state`.
381 Until a known state is reported, a successful lifecycle task establishes its target state
382 and input. Afterward, a lifecycle task succeeds once the controller reports its target
383 and input.
384 """
386 current: ClassVar[ContextVar[ControllerImpl | None]] = ContextVar("current_controller", default=None)
387 confirmation_timeout: ClassVar[float] = 5.0
388 """Seconds a lifecycle task waits after its handler returns to observe its target and input."""
390 def __init__(self, **kwargs):
391 super().__init__(**kwargs)
393 self._enable_hooks: list[Callable[[], None]] = []
394 self._disable_hooks: list[Callable[[], None]] = []
395 self._task_handlers: dict[type[Task], ExecutionHandlerCallback[Any]] = {}
396 self._execution: TaskRun | None = None
397 self._states = ControllerStateResolver()
398 self._devices = ControllerDeviceMap()
399 self._instruments: dict[str, InstrumentInfo] = {}
401 @override
402 def task_running(self):
403 return self._execution is not None and not self._execution.done()
405 @override
406 def on_enable(self, func: Callable[[], None]):
407 self._enable_hooks.append(func)
408 return func
410 @override
411 def on_disable(self, func: Callable[[], None]):
412 self._disable_hooks.append(func)
413 return func
415 @override
416 async def init_impl(self):
417 self._state = await ControllerState.recover_or_init(
418 self,
419 enable_state=ControllerEnableState(enabled=True),
420 operating_state=ControllerOperatingState(
421 current=InternalControllerState.UNKNOWN,
422 context=KeywordDict(),
423 ),
424 execution_state=TaskExecutionState(execution=None),
425 )
427 operating = self._state.operating_state
429 # A restart is not a successful command, so an unsettled state stays latched.
430 match operating.current, operating.previous, operating.target:
431 # UNKNOWN since the first start has nothing to latch.
432 case InternalControllerState.UNKNOWN, None, None:
433 latched = False
434 case (
435 InternalControllerState.UNKNOWN
436 | InternalControllerState.ERROR
437 | InternalControllerState.TRANSITION
438 ), _, _:
439 latched = True
440 case _, _, target:
441 latched = target is not None
443 await self._normalize_startup_state()
445 self._states = ControllerStateResolver(operating.context, latched=latched)
447 async def _normalize_startup_state(self):
448 async with self._state.updating(self) as update:
449 operating = self._state.operating_state
450 current = self._state.execution_state
452 # Persist legacy normalization before accepting work.
453 legacy = "context" not in operating.model_fields_set
455 if (
456 operating.current == InternalControllerState.UNKNOWN
457 and operating.target is None
458 and not legacy
459 and not current.executing
460 ):
461 return
463 events = []
465 # A pending target also identifies an interrupted lifecycle execution.
466 if (
467 operating.current == InternalControllerState.TRANSITION
468 or operating.target is not None
469 ):
470 logger.warning(f"Recovering from interrupted transition to {operating.target}")
472 if current.executing:
473 events.append(
474 TaskExecutionState(
475 finished=TaskFinishInfo(aborted=True),
476 execution=current.execution,
477 context=current.context,
478 )
479 )
481 # The persisted state describes hardware before the restart.
482 events.append(operating.derive(current=InternalControllerState.UNKNOWN, target=None))
483 await update(*events)
485 @override
486 async def attach_impl(self):
487 if self._state.enable_state.enabled:
488 await self._call_with_context(self._enable_hooks)
490 await self.handle_request(set_enable_state_request, self._set_enable_state)
491 await self.handle_request(abort_task_request, self._abort_request)
492 await self.handle_request(execute_task_request, self._execute_request)
494 await self.start_device_subscriptions()
496 @override
497 async def detach_impl(self):
498 await self.stop_device_subscriptions()
500 @override
501 def register_instrument(
502 self,
503 name: str,
504 *,
505 devices: Collection[str | DeviceClient] = (),
506 ) -> None:
507 if isinstance(devices, str):
508 raise TypeError(
509 f"Pass devices for instrument '{name}' as a collection of IDs or clients"
510 )
512 keys = tuple(
513 str(device.entity) if isinstance(device, DeviceClient) else device
514 for device in devices
515 )
516 instrument = InstrumentInfo(name=name, devices=keys)
518 if name in self._instruments:
519 raise ValueError(f"Cannot register instrument '{name}' twice")
521 self._instruments[name] = instrument
523 @override
524 def instrument_context(self, name: str) -> Context:
525 try:
526 instrument = self._instruments[name]
527 except KeyError:
528 raise KeyError(f"No instrument '{name}' is registered") from None
530 return Context(instrument.model_copy())
532 @override
533 def use_device(self, name: str, *, subscribe: list[type] | None = None) -> DeviceClient:
534 """Register a device dependency and return its client.
536 Subscribed keywords are cached for task contexts. The declarative API starts
537 subscriptions after attach hooks and stops them before detach hooks.
539 Args:
540 name: Entity ID of the device.
541 subscribe: Keyword model types to monitor.
543 Returns:
544 The device client. Cached values are available through
545 `get_device(name).subscription`.
546 """
547 device = self._devices.get_or_add(
548 name,
549 get_client_func=lambda _: self.sensorkit().device(Entity((name,))),
550 )
552 if subscribe:
553 for kw_type in subscribe:
554 device.subscription.add(kw_type)
556 return device.client
558 @override
559 def get_device(self, name: str) -> ControllerDevice:
560 return self._devices[name]
562 @override
563 def all_devices(self) -> Collection[ControllerDevice]:
564 return self._devices.values()
566 @override
567 async def start_device_subscriptions(self):
568 """Start keyword subscriptions registered through `use_device`.
570 The declarative API calls this after attach hooks. Controllers registered
571 directly can call it explicitly.
572 """
573 for device in self._devices.values():
574 await device.subscription.start()
576 @override
577 async def stop_device_subscriptions(self):
578 """Stop keyword subscriptions registered through `use_device`.
580 The declarative API calls this before detach hooks.
581 """
582 for device in self._devices.values():
583 await device.subscription.stop()
585 @override
586 async def update_context(
587 self,
588 *args,
589 **kwargs,
590 ) -> Context:
591 """Update the context of the currently executing task.
593 Merges the base context with fresh snapshots from all device keyword
594 subscriptions and additional provided values. The updated context is
595 persisted to the execution state and returned.
597 This method allows task handlers to refresh their context mid-execution,
598 incorporating the latest device state.
600 Args:
601 **kwargs: Additional literal key-value pairs to include in the context.
603 Returns:
604 The newly updated `Context` containing (in precedence order,
605 highest-last): current task context, fresh device snapshots,
606 and *kwargs*.
608 Raises:
609 RuntimeError: If called when no task is currently executing.
611 Examples:
612 Update context with latest device data during task execution:
614 >>> async def my_task_handler(self, task):
615 ... # ... some work ...
616 ... ctx = await self.update_context()
617 ... pointing = ctx.get(AltAzPointing)
619 Add custom values while updating:
621 >>> ctx = await self.update_context(iteration=5, timestamp=time.time())
622 """
623 async with self._state.updating(self) as update:
624 current = self._state.execution_state
626 if not current.executing or current.execution is None:
627 raise RuntimeError("no task executing")
629 ctx = Context(current.context)
631 for device in self._devices.values():
632 device.subscription.snapshot(into=ctx)
634 ctx.set(*args)
636 for key, value in kwargs.items():
637 ctx.set_value(key, value)
639 await update(
640 TaskExecutionState(
641 executing=current.executing,
642 aborting=current.aborting,
643 execution=current.execution,
644 context=ctx,
645 ),
646 )
648 return ctx
650 async def _set_enable_state(self, request: ControllerEnableStateRequest):
651 if request.enable == self._state.enable_state.enabled:
652 return
654 await self._state.update(self, ControllerEnableState(enabled=request.enable))
656 if request.enable:
657 await self._call_with_context(self._enable_hooks)
658 else:
659 #TODO: Abort. Need a nice way of calling a local "loopback" request.
660 # await self.call_loopback(abort_task_request, AbortRequestMessage(task_id=None))
662 await self._call_with_context(self._disable_hooks)
664 async def _abort_request(
665 self,
666 requested: AbortRequestMessage,
667 call: CallContext[None, AbortResponseMessage],
668 ):
669 async with self._state.updating(self) as update:
670 target = self._execution if self.task_running() else None
671 current = self._state.execution_state
673 # A finished runner may still be completing its request.
674 if target is None:
675 call.reject(
676 response=AbortResponseMessage(aborting=False, task_id=None),
677 reason="No task is running",
678 )
679 return
681 task_id = target.execution.task_id
683 # If given, ensure the task_id matches the latest accepted execution.
684 if requested.task_id and task_id != requested.task_id:
685 call.reject(
686 response=AbortResponseMessage(aborting=False, task_id=None),
687 reason=f"Running task {task_id} does not match",
688 )
689 return
691 logger.debug(f"aborting running task {task_id}")
692 call.accept(response=AbortResponseMessage(aborting=True, task_id=task_id))
694 # Pending work leaves its predecessor's published execution alone.
695 if current.executing and current.execution.task_id == task_id:
696 await update(
697 TaskExecutionState(
698 executing=True,
699 aborting=True,
700 execution=current.execution,
701 context=current.context,
702 ),
703 )
705 target.cancel("Aborted by remote request")
707 # Wait for the execution and its predecessors to end.
708 with contextlib.suppress(asyncio.CancelledError, Exception):
709 await call.progress_from_task(target.runner, cadence=5, ttl=10)
711 if target.done():
712 # Success.
713 await call.succeed(result=None)
714 else:
715 await call.fail()
717 async def _admit(
718 self,
719 msg: ExecuteRequestMessage,
720 call: CallContext[TaskExecutionResult, ExecuteResponseMessage],
721 ) -> TaskRun | None:
722 task = msg.task
724 async with self._state.updating(self) as update:
725 predecessor = self._execution if self.task_running() else None
726 running = TaskRun.create(
727 str(self.entity),
728 task,
729 context=msg.context,
730 expiry_time=msg.expiry_time,
731 )
733 response = ExecuteResponseMessage(execution=running.execution)
734 handler = self._task_handlers.get(type(task))
736 enabled = self._state.enable_state.enabled
738 match enabled, predecessor, msg.interrupt, running.lifecycle, handler:
739 case False, _, _, _, _:
740 reason = "Controller is disabled"
741 # Only a lifecycle task may run while the controller is between states.
742 case _, TaskRun(transition=True), _, False, _:
743 reason = "Controller is between states"
744 case _, TaskRun(), False, _, _:
745 reason = "Task already in progress"
746 case _, _, _, _, None:
747 reason = f"No handler registered for {task.task_type}"
748 case _, _, _, _, handler:
749 try:
750 # Publish the transition before an interrupted task starts stopping.
751 if running.lifecycle:
752 await self._enter_transition(running, update)
753 except asyncio.CancelledError:
754 call.reject(response=response, reason="Admission was canceled")
755 raise
756 except Exception as e:
757 reason = f"Could not publish transition ({e})"
758 else:
759 if predecessor:
760 logger.info(
761 f"Interrupting {predecessor.execution.task.task_type} task"
762 )
764 # Ownership is installed before acceptance becomes visible.
765 running.attach(handler, self._run_execution(running, predecessor))
766 self._execution = running
767 call.accept(response=response)
769 return running
771 logger.warning(f"Rejecting {task.task_type} task: {reason}")
772 call.reject(response=response, reason=reason)
774 return None
776 async def _enter_transition(self, running: TaskRun, update: StateUpdate):
777 """Publish the transition of an admitted lifecycle task.
779 On failure or cancellation, attempt to restore the prior state before propagating.
780 """
781 prior = self._state.operating_state
783 try:
784 await self._publish_operating_state(update, running)
785 except BaseException:
786 # The predecessor keeps its transition and lifecycle input.
787 with contextlib.suppress(Exception):
788 await defer_cancellation(update(prior.derive()))
790 raise
792 async def _execute_request(
793 self,
794 msg: ExecuteRequestMessage,
795 call: CallContext[TaskExecutionResult, ExecuteResponseMessage],
796 ):
797 task = msg.task
798 running = await self._admit(msg, call)
800 if running is None:
801 return
803 execution = running.execution
805 try:
806 await call.progress_from_task(running.runner, cadence=6.0, ttl=10.0)
807 except asyncio.CancelledError:
808 with self.enter_context():
809 logger.warning(f"Execution of {task.task_type} task cancelled")
811 raise
812 except Exception as e:
813 with self.enter_context():
814 logger.error(f"Error executing {task.task_type} task")
815 logger.opt(exception=e).debug(f"{task.task_type} ({execution.task_id}) failed")
816 else:
817 with self.enter_context():
818 logger.info(f"Finished {task.task_type} task")
820 await call.succeed(result=running.runner.result())
821 finally:
822 # Join this request's execution even after a successor replaced it.
823 if not running.done():
824 running.cancel()
826 try:
827 await running.wait()
828 finally:
829 if self._execution is running:
830 self._execution = None
832 # Clients treat the final event as proof the run ended, so it follows the join.
833 if not call.finalized:
834 await defer_cancellation(self._fail_call(call, task))
836 @staticmethod
837 async def _fail_call(call: CallContext, task: Task):
838 try:
839 await call.fail()
840 except Exception as e:
841 logger.warning(f"Error reporting failed {task.task_type} task ({type(e).__name__})")
843 async def _run_execution(
844 self,
845 running: TaskRun,
846 predecessor: TaskRun | None,
847 ) -> TaskExecutionResult:
848 with self.enter_context():
849 try:
850 # Cancellation targets the runner from here. Without a predecessor, nothing
851 # awaits before execution.
852 if predecessor is not None:
853 running.phase = TaskRunPhase.INTERRUPTING
855 try:
856 predecessor.cancel("Interrupted")
857 await defer_cancellation(predecessor.join())
858 except Exception as e:
859 running.fail(e)
860 raise
861 finally:
862 # Release the predecessor so repeated interruption cannot retain a chain.
863 predecessor = None
865 with running.execute() as execution:
866 logger.info(f"Executing {execution.task.task_type} task")
867 logger.debug(f"execution begun {execution=}")
869 await self._publish_start(running)
871 if not self._state.enable_state.enabled:
872 raise RuntimeError("Controller is disabled")
874 await running.handler(execution)
875 running.handler_latched_state = self._states.latch
876 await self._confirm_observed_state(running)
877 finally:
878 # Joining the runner includes settlement.
879 await defer_cancellation(self._publish_finish(running))
881 return running.result()
883 async def _confirm_observed_state(self, running: TaskRun):
884 """Wait for the controller to report the target and input once it reports known states.
886 Raises:
887 RuntimeError: If the controller reports UNKNOWN or ERROR, or does not report the
888 target and input in time.
889 """
890 target = running.execution.task.target_state()
892 if target is None or self._states.observed is None:
893 return
895 expected = StateWithInput(target, running.submitted_context)
897 try:
898 async with asyncio.timeout(self.confirmation_timeout):
899 await self._states.wait_until_observed(expected)
900 except TimeoutError as e:
901 raise RuntimeError(f"Controller did not report {target} with the task input") from e
903 async def _publish_start(self, running: TaskRun):
904 execution = running.execution
906 async with self._state.updating(self) as update:
907 # Execution context is the base for later device snapshots.
908 await defer_cancellation(
909 update(
910 TaskExecutionState(
911 executing=True, execution=execution, context=execution.context
912 )
913 )
914 )
916 async def _publish_finish(self, running: TaskRun):
917 """Publish a finished execution and its effect on the settled state.
919 Raises:
920 RuntimeError: If a new fault or mismatched observation prevents lifecycle completion.
921 """
922 events = []
923 mismatch = None
925 async with self._state.updating(self) as update:
926 if running.lifecycle:
927 mismatch = self._settle(running)
929 running.phase = TaskRunPhase.FINISHED
931 # Record a finish once execution has begun.
932 if running.start_time is not None:
933 events.append(
934 TaskExecutionState(finished=running.finish_info, execution=running.execution)
935 )
937 await self._publish_operating_state(update, self._execution, *events)
939 if mismatch is not None:
940 raise mismatch
942 def _settle(self, running: TaskRun) -> RuntimeError | None:
943 """Apply a finished lifecycle task to the settled state.
945 Returns:
946 A lifecycle confirmation error, or None.
947 """
948 finish = running.finish_info
949 target = running.execution.task.target_state()
950 states = self._states
952 # Reports may have arrived while waiting for the update lock.
953 match finish:
954 case TaskFinishInfo(error=False, aborted=False) if (
955 (latch := states.latch) is not None and latch is not running.handler_latched_state
956 ):
957 mismatch = RuntimeError(f"Controller reported {latch.state} before settling")
958 case TaskFinishInfo(error=False, aborted=False) if target is not None and not (
959 states.confirms(StateWithInput(target, running.submitted_context))
960 ):
961 mismatch = RuntimeError(f"Controller no longer reports {target} with the task input")
962 case _:
963 mismatch = None
965 if mismatch is not None:
966 running.fail(mismatch)
968 states.record_finish(running)
970 return mismatch
972 def _derive_operating_state(self, newest: TaskRun | None) -> ControllerOperatingState:
973 """Derive the operating state from the newest task run and the settled state."""
974 settled = self._states.settled
976 match newest:
977 case TaskRun(transition=True) as run:
978 current = InternalControllerState.TRANSITION
979 target = run.execution.task.target_state()
980 context = run.submitted_context if target is not None else settled.context
981 case _:
982 current, target, context = settled.state, None, settled.context
984 return self._state.operating_state.derive(current=current, target=target, context=context)
986 async def _publish_operating_state(
987 self, update: StateUpdate, newest: TaskRun | None, *events: Event
988 ):
989 """Publish execution events and any operating-state change."""
990 published = self._state.operating_state
991 derived = self._derive_operating_state(newest)
993 if (derived.current, derived.target, derived.context) != (
994 published.current,
995 published.target,
996 published.context,
997 ):
998 events = (*events, derived)
1000 if events:
1001 await defer_cancellation(update(*events))
1003 @override
1004 def add_task_handler[T: Task](
1005 self,
1006 task_model: type[T],
1007 *,
1008 task_callback: TaskHandlerCallback[T] | None = None,
1009 execution_callback: ExecutionHandlerCallback[T] | None = None,
1010 ) -> None:
1011 match task_callback, execution_callback:
1012 case None, None:
1013 raise TypeError("A task handler requires a task or execution callback")
1014 case _, None:
1015 handler = lambda execution: task_callback(execution.task)
1016 case None, _:
1017 handler = execution_callback
1018 case _:
1019 raise TypeError("A task handler takes one callback")
1021 if task_model in self._task_handlers:
1022 raise RuntimeError("multiple handlers for task type")
1024 self._task_handlers[task_model] = handler
1026 @override
1027 def task_handler[T: Task](self, task_model: type[T]):
1028 def decorator(func: TaskHandlerCallback[T]):
1029 self.add_task_handler(task_model, task_callback=func)
1030 return func
1032 return decorator
1034 @override
1035 def entity_info(self) -> EntityInfo:
1036 return EntityInfo(
1037 entity_type="controller",
1038 details=ControllerDetails(
1039 published_keywords=frozenset(self._published_keywords),
1040 supported_tasks=[t.__name__ for t in self._task_handlers.keys()],
1041 controlled_devices=list(self._devices.keys()),
1042 instruments=tuple(info.model_copy() for info in self._instruments.values()),
1043 ),
1044 )
1046 @overload
1047 async def report_state(self, state: KnownControllerState, context: KeywordDict): ...
1049 @overload
1050 async def report_state(self, state: LatchedControllerState): ...
1052 @override
1053 async def report_state(
1054 self,
1055 state: InternalControllerState,
1056 context: KeywordDict | None = None,
1057 ):
1058 match state, context:
1059 case InternalControllerState.TRANSITION, _:
1060 raise ValueError("A transition requires a lifecycle task")
1061 case InternalControllerState.UNKNOWN | InternalControllerState.ERROR, None:
1062 pass
1063 case InternalControllerState.UNKNOWN | InternalControllerState.ERROR, _:
1064 raise ValueError(f"{state} keeps the recorded lifecycle input")
1065 case _, None:
1066 raise ValueError(f"{state} requires its lifecycle input")
1067 case _:
1068 context = copy.deepcopy(context)
1070 async with self._state.updating(self) as update:
1071 self._states.record_observed(state, context)
1072 await self._publish_operating_state(update, self._execution)