Coverage for core / src / sensorkit / auto / supervisor.py: 94%

184 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"""Compare controller state with the state lifecycle procedures expect.""" 

3 

4from __future__ import annotations 

5 

6import asyncio 

7import contextlib 

8from collections.abc import Iterator 

9from typing import TYPE_CHECKING, ClassVar 

10 

11from loguru import logger 

12 

13from sensorkit.auto.procedures import ControllerFailure 

14from sensorkit.common.aio import AsyncObserver, cleanup_future, defer_cancellation 

15from sensorkit.common.keyword import KeywordDict 

16from sensorkit.core.controller import ( 

17 ControllerMonitor, 

18 ControllerOperatingState, 

19 ControllerState, 

20 ControllerStateUnknown, 

21 InternalControllerState, 

22) 

23from sensorkit.core.task import TaskExecution 

24 

25if TYPE_CHECKING: 

26 from sensorkit.auto.failure import FailureState 

27 

28SETTLED_STATES = frozenset( 

29 { 

30 InternalControllerState.OPERATE, 

31 InternalControllerState.STANDBY, 

32 InternalControllerState.SHUTDOWN, 

33 } 

34) 

35"""Controller states that can satisfy a normal lifecycle demand.""" 

36 

37 

38class ControllerStateSupervisor: 

39 """Detect controller states that differ from the state lifecycle procedures expect. 

40 

41 The supervisor stores a local expectation separately from controller state. 

42 The expectation has four forms: 

43 

44 - None before the first settled controller state, allowing startup to adopt that state. 

45 - TRANSITION while a commanded lifecycle task is pending. 

46 - A settled state verified by a procedure. 

47 - UNKNOWN after a failure or an unconfirmed task, until another command or confirmation. 

48 

49 During a commanded transition, each mismatch has a grace period. Receiving TRANSITION 

50 clears the deadline, and a later mismatch starts a new grace period. Leaving a settled 

51 expected state or exceeding the grace period counts one controller failure and sets the 

52 expectation to UNKNOWN. A context-only change does not count as a failure. 

53 

54 Monitor updates and fresh reads advance the same controller state by event ID. Older queued 

55 updates cannot replace a state that a fresh read has already confirmed. 

56 """ 

57 

58 state_reads: ClassVar[int] = 3 

59 """Attempts to read controller state after task completion.""" 

60 

61 state_read_delay: ClassVar[float] = 0.5 

62 """Seconds between failed state reads.""" 

63 

64 def __init__( 

65 self, 

66 monitor: ControllerMonitor, 

67 failure_state: FailureState, 

68 *, 

69 transition_grace: float, 

70 ): 

71 """Create a supervisor for a started monitor. 

72 

73 Args: 

74 monitor: A controller monitor whose start method has completed. 

75 failure_state: Failure history shared across reactor restarts. 

76 transition_grace: Seconds a commanded transition may go without the controller 

77 reporting the expected state. 

78 

79 Raises: 

80 ValueError: If `transition_grace` is not positive. 

81 """ 

82 if not transition_grace > 0: 

83 raise ValueError(f"transition_grace must be positive, got {transition_grace}") 

84 

85 self.controller = monitor.controller 

86 self.failure_state = failure_state 

87 self.transition_grace = transition_grace 

88 self.failed = asyncio.Event() 

89 """Set when a controller failure is detected or supervision ends. 

90 

91 A new expectation clears this event while supervision is running. Failure history 

92 remains in `FailureState`. Once supervision ends, the event remains set. 

93 """ 

94 self._monitor = monitor 

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

96 self._expected: InternalControllerState | None = None 

97 self._expected_changed = asyncio.Event() 

98 self._deadline: float | None = None 

99 self._observed_state: ControllerOperatingState | None = None 

100 self._ready = asyncio.Event() 

101 self._task: asyncio.Task[None] | None = None 

102 self._error: BaseException | None = None 

103 

104 @property 

105 def expected(self) -> InternalControllerState | None: 

106 """The expected state, or None before the first settled controller state.""" 

107 return self._expected 

108 

109 async def start(self): 

110 """Start supervision and wait until the initial controller state is processed. 

111 

112 Failure or cancellation stops supervision and releases its subscriptions. 

113 The caller remains responsible for stopping the monitor. 

114 """ 

115 if self._task is not None: 

116 raise RuntimeError("A controller state supervisor can only be started once") 

117 

118 self._task = asyncio.create_task(self._run()) 

119 

120 # Notify waiters even if the task is canceled before it starts. 

121 self._task.add_done_callback(lambda _: self._close()) 

122 

123 try: 

124 await self._ready.wait() 

125 self._check_health() 

126 except BaseException: 

127 await defer_cancellation(self.stop()) 

128 raise 

129 

130 async def stop(self): 

131 """Stop supervision and release its subscriptions. 

132 

133 The caller remains responsible for stopping the monitor. 

134 """ 

135 if self._task is None: 

136 return 

137 

138 self._task.cancel() 

139 await asyncio.wait((self._task,)) 

140 

141 def healthy(self) -> bool: 

142 """Whether supervision is running with valid controller state and a healthy monitor.""" 

143 return ( 

144 self._task is not None 

145 and not self._task.done() 

146 and self._observed_state is not None 

147 and self._monitor.healthy() 

148 ) 

149 

150 def _check_health(self): 

151 """Raise if state monitoring or supervision is unavailable.""" 

152 if not self.healthy(): 

153 raise ControllerStateUnknown( 

154 f"{self.controller.entity} state supervision is unavailable" 

155 ) from (self._error or self._monitor.error) 

156 

157 @property 

158 def state(self) -> ControllerOperatingState: 

159 """Copy of the newest controller state processed by supervision. 

160 

161 Raises: 

162 ControllerStateUnknown: If state monitoring failed or supervision ended. 

163 """ 

164 self._check_health() 

165 return self._observed_state.model_copy(deep=True) 

166 

167 async def refresh(self) -> ControllerState: 

168 """Read controller state and process its operating state in event order. 

169 

170 Older updates do not replace a newer processed state. The returned snapshot is the 

171 complete controller state read from the backend. 

172 

173 Raises: 

174 ControllerFailure: If controller state cannot be read after retries. 

175 ControllerStateUnknown: If state monitoring failed or supervision is unavailable. 

176 """ 

177 self._check_health() 

178 last_error = None 

179 

180 for attempt in range(1, self.state_reads + 1): 

181 try: 

182 snapshot = await self.controller.kv_get_model(ControllerState) 

183 except Exception as error: 

184 last_error = error 

185 logger.warning(f"Could not read {self.controller.entity} state ({error!r})") 

186 

187 if attempt < self.state_reads: 

188 await asyncio.sleep(self.state_read_delay) 

189 else: 

190 self._check_health() 

191 self._process_state(snapshot.operating_state) 

192 return snapshot 

193 

194 raise ControllerFailure( 

195 f"Controller state unread for {self.controller.entity}" 

196 ) from last_error 

197 

198 async def verify( 

199 self, state: InternalControllerState, context: KeywordDict | None = None 

200 ) -> ControllerState: 

201 """Read fresh state and verify a lifecycle result without changing the expectation. 

202 

203 Raises: 

204 ControllerFailure: If state cannot be read or the state or context differs. 

205 ControllerStateUnknown: If state monitoring failed or supervision is unavailable. 

206 """ 

207 try: 

208 snapshot = await self.refresh() 

209 

210 if not self.state.matches(state, context or KeywordDict()): 

211 raise ControllerFailure( 

212 f"Controller did not reach {state} with the requested lifecycle context" 

213 ) 

214 except BaseException: 

215 self.invalidate() 

216 raise 

217 

218 return snapshot 

219 

220 def running_execution(self) -> TaskExecution | None: 

221 """Return the execution the controller last reported running, if any. 

222 

223 Raises: 

224 ControllerStateUnknown: If state monitoring failed or stopped. 

225 """ 

226 state = self._monitor.state.execution_state 

227 return state.execution if state.executing else None 

228 

229 def settled(self, state: InternalControllerState, context: KeywordDict) -> bool: 

230 """Return whether controller state and context match a valid local expectation. 

231 

232 No transition may be pending. An unset expectation allows startup adoption. 

233 An UNKNOWN expectation requires another lifecycle command. 

234 

235 Raises: 

236 ControllerStateUnknown: If state monitoring failed or supervision ended. 

237 """ 

238 return self._expected in (None, state) and self.state.matches(state, context) 

239 

240 @contextlib.contextmanager 

241 def state_changes(self) -> Iterator[asyncio.Queue[ControllerOperatingState]]: 

242 """Subscribe to operating state changes after comparison with the expected state. 

243 

244 The queue retains only the latest state and shuts down when supervision ends. 

245 

246 Raises: 

247 ControllerStateUnknown: If state monitoring failed or supervision ended. 

248 """ 

249 self._check_health() 

250 

251 with self._observer.subscription(maxsize=1) as queue: 

252 yield queue 

253 

254 def expect_transition(self): 

255 """Expect the controller to report TRANSITION for a lifecycle task about to be sent.""" 

256 self._expect(InternalControllerState.TRANSITION) 

257 

258 async def confirm( 

259 self, state: InternalControllerState, context: KeywordDict | None = None 

260 ) -> ControllerState: 

261 """Verify fresh controller state and context, then establish the expectation.""" 

262 snapshot = await self.verify(state, context) 

263 self._expect(state) 

264 return snapshot 

265 

266 def invalidate(self): 

267 """Set the expectation to UNKNOWN until another lifecycle command or confirmation.""" 

268 self._expect(InternalControllerState.UNKNOWN) 

269 

270 def _expect(self, state: InternalControllerState): 

271 self._expected = state 

272 self._deadline = None 

273 self._expected_changed.set() 

274 

275 if not self._ended(): 

276 self.failed.clear() 

277 

278 def _ended(self) -> bool: 

279 return self._task is not None and self._task.done() 

280 

281 async def _run(self): 

282 try: 

283 with self._monitor.state_changes() as state_changes: 

284 while True: 

285 self._expected_changed.clear() 

286 state = await self._next(state_changes) 

287 self._process_state(state) 

288 except (asyncio.QueueShutDown, ControllerStateUnknown): 

289 # The state accessor raises when state monitoring fails or supervision ends. 

290 pass 

291 except Exception as e: 

292 self._error = e 

293 logger.opt(exception=e).error(f"{self.controller.entity} state supervision failed") 

294 

295 def _close(self): 

296 """Close state subscriptions and wake failure waiters.""" 

297 self._observer.close() 

298 self.failed.set() 

299 self._ready.set() 

300 

301 def _process_state(self, state: ControllerOperatingState | None): 

302 """Accept newer state updates and compare the processed state with the expectation.""" 

303 current = self._observed_state 

304 newer = state is not None and ( 

305 current is None or state.event_id.int > current.event_id.int 

306 ) 

307 

308 if newer: 

309 self._observed_state = state.model_copy(deep=True) 

310 

311 if self._observed_state is not None: 

312 self._evaluate(asyncio.get_running_loop().time()) 

313 self._ready.set() 

314 

315 if newer: 

316 self._observer.notify(self._observed_state) 

317 

318 async def _next( 

319 self, 

320 state_changes: asyncio.Queue[ControllerOperatingState], 

321 ) -> ControllerOperatingState | None: 

322 """Wait for a state update, expectation change, or grace expiry. 

323 

324 Return None when an expectation change or grace expiry ends the wait without a state. 

325 """ 

326 if not state_changes.empty() or self._observed_state is None: 

327 return await state_changes.get() 

328 

329 loop = asyncio.get_running_loop() 

330 timeout = None if self._deadline is None else max(0.0, self._deadline - loop.time()) 

331 next_state = asyncio.ensure_future(state_changes.get()) 

332 changed = asyncio.ensure_future(self._expected_changed.wait()) 

333 

334 try: 

335 await asyncio.wait( 

336 (next_state, changed), timeout=timeout, return_when=asyncio.FIRST_COMPLETED 

337 ) 

338 finally: 

339 changed.cancel() 

340 

341 # Preserve a state update that arrives while the waiters are being canceled. 

342 if not next_state.done(): 

343 next_state.cancel() 

344 

345 await asyncio.wait((next_state, changed)) 

346 cleanup_future(changed) 

347 

348 if next_state.cancelled(): 

349 return None 

350 

351 return next_state.result() 

352 

353 def _evaluate(self, now: float): 

354 """Compare the latest received controller state with the expected state.""" 

355 actual = self._observed_state 

356 

357 match self._expected: 

358 case None: 

359 if actual.current in SETTLED_STATES and actual.target is None: 

360 self._expected = actual.current 

361 

362 return 

363 case InternalControllerState.UNKNOWN: 

364 return 

365 case InternalControllerState.TRANSITION: 

366 matched = actual.current == InternalControllerState.TRANSITION 

367 case expected if actual.current != expected: 

368 self._fail(f"{self.controller.entity} left {expected} ({actual.current})", now) 

369 return 

370 case _: 

371 matched = True 

372 

373 if matched: 

374 self._deadline = None 

375 elif self._deadline is None: 

376 self._deadline = now + self.transition_grace 

377 elif now >= self._deadline: 

378 self._fail( 

379 f"{self.controller.entity} reported {actual.current} for longer than " 

380 f"{self.transition_grace} s during a lifecycle task", 

381 now, 

382 ) 

383 

384 def _fail(self, message: str, now: float): 

385 """Record one controller failure and invalidate the local expectation.""" 

386 logger.error(message) 

387 self._expected = InternalControllerState.UNKNOWN 

388 self._deadline = None 

389 self.failure_state.record_failure(now, ControllerFailure(message)) 

390 self.failed.set()