Coverage for core / src / sensorkit / auto / lifecycle.py: 97%
125 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
5from typing import ClassVar, Literal, overload
7from loguru import logger
8from pydantic import BaseModel
10from sensorkit.auto.failure import FailureState, FailureStateSnapshot
11from sensorkit.auto.procedures import (
12 ControllerUnrecoverable,
13 DemandState,
14 LifecycleProcedure,
15 LifecycleStep,
16 OperateProcedure,
17 ShutdownProcedure,
18 StandbyProcedure,
19)
20from sensorkit.auto.reactor import ControllerReactor
21from sensorkit.auto.supervisor import ControllerStateSupervisor
22from sensorkit.common.aio import defer_cancellation
23from sensorkit.core.controller import ControllerClient, ControllerMonitor, InternalControllerState
24from sensorkit.core.program import ProgramClient
25from sensorkit.core.task import TaskContextMap
28class LifecycleState(BaseModel):
29 """Observed state of one controller lifecycle."""
31 step: LifecycleStep
32 """The lifecycle step in progress."""
33 failure_state: FailureStateSnapshot
34 """Failure counts, current procedure failure, and retry and recovery timing."""
35 last_reactor_error: str | None
36 """The most recent reactor failure, retained across restarts."""
39class ControllerLifecycle:
40 """Maintain the demanded controller state and restart failed reactors.
42 Each session starts a controller monitor and a state supervisor, then runs a reactor while
43 the lifecycle is enabled. Observation failures and offline controllers trigger a restart
44 after an increasing delay. Demand, enablement, and failure state persist across restarts.
45 """
47 procedures: ClassVar[dict[InternalControllerState, type[LifecycleProcedure]]] = {
48 InternalControllerState.OPERATE: OperateProcedure,
49 InternalControllerState.STANDBY: StandbyProcedure,
50 InternalControllerState.SHUTDOWN: ShutdownProcedure,
51 }
52 """Procedures for each supported demand state."""
54 settle_timeout: ClassVar[float] = 300.0
55 """Maximum time, in seconds, to wait for an existing lifecycle task that matches demand."""
57 restart_delay: ClassVar[float] = 1.0
58 """Seconds before the first reactor restart."""
60 restart_delay_max: ClassVar[float] = 60.0
61 """Maximum restart delay in seconds. A reactor running this long resets the delay."""
63 def __init__(
64 self,
65 *,
66 transition_grace: float = 10.0,
67 ):
68 """Create a lifecycle that does nothing until started and enabled.
70 Args:
71 transition_grace: Maximum seconds of disagreement with the expected state during
72 a commanded lifecycle transition. Time in TRANSITION does not count toward
73 this limit.
75 Raises:
76 ValueError: If `transition_grace` is not positive.
77 """
78 if not transition_grace > 0:
79 raise ValueError(f"transition_grace must be positive, got {transition_grace}")
81 self.transition_grace = transition_grace
82 self.failure_state = FailureState()
83 self.last_error: BaseException | None = None
84 """The most recent reactor failure, retained across restarts."""
85 self._demand = DemandState(state=None)
86 self._enabled = asyncio.Event()
87 self._reactor: ControllerReactor | None = None
89 def start(
90 self,
91 controller: ControllerClient,
92 *,
93 task_group=asyncio,
94 ):
95 """Bind to *controller* and launch the lifecycle loop in *task_group*."""
96 self.controller = controller
97 self._main_task = task_group.create_task(self._supervise())
99 async def stop(self):
100 """Cancel the lifecycle loop and wait for it to finish.
102 Canceling the caller cancels the loop again and stops procedure cleanup without sending
103 further controller or program requests.
104 """
105 self._main_task.cancel()
107 try:
108 # The loop's own cancellation is expected and does not propagate.
109 await asyncio.wait((self._main_task,))
110 except asyncio.CancelledError:
111 self._main_task.cancel()
112 raise
114 if not self._main_task.cancelled():
115 self._main_task.result()
117 def enable(self):
118 """Allow the lifecycle to issue demand commands to the controller."""
119 self._enabled.set()
121 def disable(self):
122 """Withdraw demand and request interruption of the current procedure."""
123 self._enabled.clear()
124 self._demand = DemandState(state=None)
125 self._wake()
127 @property
128 def enabled(self):
129 """True if the lifecycle is currently allowed to command the controller."""
130 return self._enabled.is_set()
132 @property
133 def demand_state(self):
134 """The latest demand, available to the reactor and procedures as soon as it is set."""
135 return self._demand
137 @property
138 def step(self) -> LifecycleStep:
139 """The current lifecycle step, or WAIT when no reactor is running."""
140 return LifecycleStep.WAIT if self._reactor is None else self._reactor.step
142 def status(self, monotonic: float) -> LifecycleState:
143 """Return a detached snapshot of the lifecycle state.
145 Args:
146 monotonic: The shared monotonic reference for evaluating retry deadlines.
147 """
148 error = self.last_error
150 return LifecycleState(
151 step=self.step,
152 failure_state=self.failure_state.snapshot(monotonic),
153 last_reactor_error=None if error is None else f"{type(error).__name__}: {error}",
154 )
156 @overload
157 def set_demand_state(
158 self,
159 demand: Literal[InternalControllerState.OPERATE],
160 *,
161 contexts: TaskContextMap = ...,
162 program: ProgramClient,
163 interrupt: bool = ...,
164 program_interrupt: bool = ...,
165 ): ...
167 @overload
168 def set_demand_state(
169 self,
170 demand: Literal[InternalControllerState.STANDBY, InternalControllerState.SHUTDOWN],
171 *,
172 contexts: TaskContextMap = ...,
173 interrupt: bool = ...,
174 ): ...
176 def set_demand_state(self, demand: InternalControllerState, **kwargs):
177 """Set demand and return whether its state, contexts, or program changed."""
178 if demand not in self.procedures:
179 raise ValueError(f"Cannot demand controller state {demand}")
181 # Snapshot contexts so caller mutations cannot change the demand.
182 if (contexts := kwargs.get("contexts")) is not None:
183 kwargs["contexts"] = contexts.model_copy(deep=True)
185 state = DemandState(demand, **kwargs)
186 changed = state != self._demand
187 self._demand = state
188 self._wake()
190 return changed
192 def _wake(self):
193 if self._reactor is not None:
194 self._reactor.wake()
196 async def _supervise(self):
197 loop = asyncio.get_running_loop()
198 delay = self.restart_delay
200 while True:
201 await self._enabled.wait()
202 started = loop.time()
203 error, achieved = await self._session()
205 # Commanding the demanded state or outlasting the longest delay resets the backoff.
206 if error is None or achieved or loop.time() - started >= self.restart_delay_max:
207 delay = self.restart_delay
209 if error is None:
210 continue
212 self.last_error = error
214 logger.opt(exception=error).error(
215 f"{self.controller.entity} lifecycle restarting in {delay} s: {error}"
216 )
217 await asyncio.sleep(delay)
218 delay = min(delay * 2, self.restart_delay_max)
220 async def _session(self) -> tuple[Exception | None, bool]:
221 """Run a reactor with its monitor and state supervisor.
223 Returns:
224 The reactor's failure, if any, and whether it ever commanded the demanded state.
225 """
226 monitor = ControllerMonitor(self.controller)
227 supervisor = None
228 reactor = None
230 try:
231 await monitor.start()
233 supervisor = ControllerStateSupervisor(
234 monitor,
235 self.failure_state,
236 transition_grace=self.transition_grace,
237 )
238 await supervisor.start()
240 reactor = ControllerReactor(self, supervisor)
241 self._reactor = reactor
242 await reactor.run()
243 except ControllerUnrecoverable as e:
244 # Emergency shutdown requires operator intervention.
245 self.last_error = e
246 self.disable()
247 except Exception as e:
248 return e, reactor is not None and reactor.achieved_once
249 finally:
250 self._reactor = None
252 # Keep state monitoring cleanup failures from propagating to the caller's task group.
253 try:
254 await self._release(monitor, supervisor)
255 except Exception as e:
256 logger.opt(exception=e).error(
257 f"{self.controller.entity} state monitoring cleanup failed"
258 )
260 return None, reactor is not None and reactor.achieved_once
262 @staticmethod
263 async def _release(monitor: ControllerMonitor, supervisor: ControllerStateSupervisor | None):
264 """Stop the supervisor, then the monitor, completing both despite cancellation."""
265 try:
266 if supervisor is not None:
267 await defer_cancellation(supervisor.stop())
268 finally:
269 await defer_cancellation(monitor.stop())