Coverage for core / src / sensorkit / auto / procedures.py: 92%

471 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"""Lifecycle procedures that track controller tasks and manage program tasking.""" 

3 

4from __future__ import annotations 

5 

6import asyncio 

7import contextlib 

8import copy 

9from abc import ABC, abstractmethod 

10from dataclasses import dataclass, field 

11from enum import StrEnum, auto 

12from typing import TYPE_CHECKING, ClassVar, Literal, final, override 

13 

14from loguru import logger 

15 

16from sensorkit.backend.base import Entity, KeyNotFound 

17from sensorkit.backend.request import CallRejected 

18from sensorkit.common.aio import cleanup_future, defer_cancellation, interruptible_wait 

19from sensorkit.common.keyword import KeywordDict 

20from sensorkit.core.controller import ( 

21 ControllerState, 

22 ControllerStateUnknown, 

23 InternalControllerState, 

24) 

25from sensorkit.core.entity import EntityClient 

26from sensorkit.core.executor import TaskCall, TaskFailed, TaskOutcomeUnknown 

27from sensorkit.core.program import ( 

28 ProgramActivation, 

29 ProgramActiveState, 

30 ProgramClient, 

31 ProgramState, 

32 TaskingError, 

33 TaskingLoopState, 

34 TaskingStartupFailed, 

35) 

36from sensorkit.core.task import ( 

37 InitTask, 

38 RecoverTask, 

39 ShutdownTask, 

40 StandbyTask, 

41 Task, 

42 TaskContextMap, 

43) 

44 

45if TYPE_CHECKING: 

46 from sensorkit.auto.supervisor import ControllerStateSupervisor 

47 

48LIFECYCLE_TASK_TYPES: dict[InternalControllerState, str] = { 

49 InternalControllerState.OPERATE: "init", 

50 InternalControllerState.STANDBY: "standby", 

51 InternalControllerState.SHUTDOWN: "shutdown", 

52} 

53"""Lifecycle task types for the demandable controller states.""" 

54 

55 

56class LifecycleStep(StrEnum): 

57 """The lifecycle operation currently in progress.""" 

58 

59 INIT = auto() 

60 TASKING = auto() 

61 STANDBY = auto() 

62 SHUTDOWN = auto() 

63 RECOVER = auto() 

64 WAIT = auto() 

65 

66 

67@dataclass(slots=True, frozen=True) 

68class DemandState: 

69 """Demanded controller state, task contexts, and program.""" 

70 

71 state: InternalControllerState | None 

72 contexts: TaskContextMap | None = None 

73 program: ProgramClient | None = None 

74 

75 # Interruption flags wake the reactor but do not affect demand equality. 

76 interrupt: bool = field(default=False, compare=False) 

77 """Abort the current procedure when this demand replaces it.""" 

78 program_interrupt: bool = field(default=False, compare=False) 

79 """Allow aborting program tasking at OPERATE with no transition or lifecycle call pending.""" 

80 

81 def lifecycle_context(self, state: InternalControllerState | None = None) -> KeywordDict: 

82 """Return the task context for a lifecycle state, defaulting to the demanded state. 

83 

84 Return an empty context if no contexts or state are set. 

85 """ 

86 state = self.state if state is None else state 

87 

88 if self.contexts is None or state is None: 

89 return KeywordDict() 

90 

91 return copy.deepcopy(self.contexts.get(LIFECYCLE_TASK_TYPES[state])) 

92 

93 

94class ProcedureError(Exception): 

95 """A procedure failed and requires a delayed retry.""" 

96 

97 

98class ControllerFailure(ProcedureError): 

99 """A procedure failure that contributes to the controller's recovery threshold.""" 

100 

101 

102class ControllerIndeterminate(Exception): 

103 """Controller task execution or program tasking could not be confirmed stopped.""" 

104 

105 

106class ControllerOffline(Exception): 

107 """The controller does not hold its lease.""" 

108 

109 

110class ControllerUnrecoverable(Exception): 

111 """Automatic recovery was exhausted and emergency shutdown succeeded. 

112 

113 Operator intervention is required before lifecycle control resumes. 

114 """ 

115 

116 

117class LifecycleProcedure(ABC): 

118 """Apply demand and track dispatched tasks through cleanup. 

119 

120 A stop request or state logic failure triggers graceful cleanup. An abort request or failed 

121 graceful cleanup triggers abort cleanup. Dispatched tasks and registered futures remain 

122 tracked when the logic awaiting them is interrupted. 

123 

124 Returning from state logic sends no cleanup requests. Canceling the procedure stops local 

125 cleanup without sending further controller or program requests. Work that cannot be 

126 confirmed stopped is marked unresolved, causing the reactor to restart. 

127 """ 

128 

129 graceful_budget: ClassVar[float] = 150.0 

130 """Time limit in seconds for each graceful cleanup stage before escalating to abort.""" 

131 

132 abort_budget: ClassVar[float] = 15.0 

133 """Time limit in seconds for each abort cleanup stage.""" 

134 

135 expects_target: ClassVar[bool] = True 

136 """Whether lifecycle task dispatch establishes a TRANSITION expectation.""" 

137 

138 def __init__(self, supervisor: ControllerStateSupervisor, demand: DemandState): 

139 self.supervisor = supervisor 

140 self.demand = demand 

141 self.step = LifecycleStep.WAIT 

142 """The lifecycle operation in progress.""" 

143 self.interrupt: Literal["stop", "abort"] | None = None 

144 """The most severe interruption requested.""" 

145 self.achieved = False 

146 """Whether this procedure confirmed the required controller state and lifecycle context.""" 

147 self.commanded = False 

148 """Whether this procedure's own lifecycle task established the confirmed state.""" 

149 self.unresolved = False 

150 """Whether tracked tasks, cleanup futures, or program tasking may still be active.""" 

151 self.cleanup_errors: list[BaseException] = [] 

152 self._calls: list[TaskCall] = [] 

153 self._cleanup_futures: set[asyncio.Future] = set() 

154 self._logic: asyncio.Task[None] | None = None 

155 self._stopping: asyncio.Task[bool] | None = None 

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

157 

158 @final 

159 def start(self): 

160 """Schedule the procedure.""" 

161 if not self.expects_target: 

162 self.supervisor.invalidate() 

163 

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

165 

166 async def _run(self): 

167 logger.debug(f"{type(self).__name__} starting") 

168 

169 controller = self.supervisor.controller 

170 

171 try: 

172 # Check the controller's lease before starting procedure logic. 

173 if self.interrupt is None and not await controller.is_online(): 

174 raise ControllerOffline(f"{controller.entity} is offline") 

175 

176 # A procedure interrupted before its first step has nothing to run. 

177 if self.interrupt is None: 

178 self._logic = asyncio.create_task(self.state_logic()) 

179 await self._finish(self._logic) 

180 

181 # Failed logic escalates to a graceful stop. 

182 if not self._logic.cancelled() and self._logic.exception() is not None: 

183 self.request_stop() 

184 

185 if self.interrupt == "stop": 

186 self._stopping = asyncio.create_task(self._stop()) 

187 await self._finish(self._stopping) 

188 

189 # Work that did not end gracefully is aborted. 

190 if self.interrupt != "abort" and not self._stopping.result(): 

191 self.request_abort() 

192 

193 if self.interrupt == "abort": 

194 await self._abort() 

195 finally: 

196 self.unresolved |= any(not future.done() for future in self._owned()) or any( 

197 isinstance(call.error(), TaskOutcomeUnknown) for call in self._calls 

198 ) 

199 

200 for error in self.cleanup_errors: 

201 logger.opt(exception=error).warning( 

202 f"{type(self).__name__} cleanup failed: {error}" 

203 ) 

204 

205 if (error := self._failure()) is not None: 

206 raise error 

207 

208 @staticmethod 

209 async def _finish(stage: asyncio.Task): 

210 """Wait for a stage, canceling and joining it if this wait is canceled.""" 

211 try: 

212 await asyncio.wait((stage,)) 

213 except asyncio.CancelledError: 

214 stage.cancel() 

215 await defer_cancellation(asyncio.wait((stage,))) 

216 raise 

217 

218 async def _stop(self) -> bool: 

219 """Wait for tracked tasks and futures to finish, then run the stop logic. 

220 

221 Returns: 

222 Whether tracked work and stop logic finished within their time limits. 

223 """ 

224 if await interruptible_wait(self._owned(), timeout=self.graceful_budget): 

225 return False 

226 

227 await self._read_ended() 

228 

229 try: 

230 async with asyncio.timeout(self.graceful_budget): 

231 await self.stop_logic() 

232 except Exception as e: 

233 self.cleanup_errors.append(e) 

234 return False 

235 

236 return True 

237 

238 async def _abort(self): 

239 """Abort tracked tasks, cancel registered futures, then run the abort logic.""" 

240 for call in self._calls: 

241 call.abort() 

242 

243 for future in self._cleanup_futures: 

244 future.cancel("Procedure abort") 

245 

246 if await interruptible_wait(self._owned(), timeout=self.abort_budget): 

247 logger.error(f"{type(self).__name__} owned work did not end after abort") 

248 

249 await self._read_ended() 

250 

251 try: 

252 async with asyncio.timeout(self.abort_budget): 

253 await self.abort_logic() 

254 except Exception as e: 

255 self.cleanup_errors.append(e) 

256 

257 def _owned(self) -> list[asyncio.Future]: 

258 """Return completion futures for tracked task calls and registered cleanup work.""" 

259 return [*(call.future() for call in self._calls), *self._cleanup_futures] 

260 

261 async def _read_ended(self): 

262 """Refresh controller state after an interrupted task call finishes. 

263 

264 The task may have changed state before the monitor received the update. 

265 """ 

266 if any(self._ended(call) for call in self._calls): 

267 with contextlib.suppress(ControllerFailure, ControllerStateUnknown): 

268 await self.supervisor.refresh() 

269 

270 def _failure(self) -> BaseException | None: 

271 """Return the primary failure of a finished procedure.""" 

272 logic = self._logic 

273 

274 if logic is not None and not logic.cancelled() and (error := logic.exception()): 

275 return error 

276 

277 # A request can fail after interruption ended the logic that sent it. 

278 for call in self._calls: 

279 match cause := call.error(): 

280 case CallRejected(): 

281 error = ProcedureError(f"{call.task.task_type} task rejected") 

282 case TaskFailed(aborted=False): 

283 error = ControllerFailure(f"{call.task.task_type} task failed") 

284 case _: 

285 continue 

286 

287 error.__cause__ = cause 

288 return error 

289 

290 return next(iter(self.cleanup_errors), None) 

291 

292 def request_stop(self): 

293 """Request a graceful end, letting sent requests and tasking finish.""" 

294 if self.interrupt is None: 

295 self.interrupt = "stop" 

296 

297 if self._logic is not None: 

298 self._logic.cancel() 

299 

300 def request_abort(self): 

301 """Request abort cleanup, interrupting state logic or graceful cleanup.""" 

302 if self.interrupt != "abort": 

303 self.interrupt = "abort" 

304 

305 for stage in (self._logic, self._stopping): 

306 if stage is not None: 

307 stage.cancel() 

308 

309 def may_dispatch(self) -> bool: 

310 """Return whether the procedure may start another operation. 

311 

312 Interruption or unhealthy state supervision prevents further operations. 

313 """ 

314 return self.interrupt is None and self.supervisor.healthy() 

315 

316 def _check_dispatch(self): 

317 """Raise cancellation if the procedure may not start another operation.""" 

318 if not self.may_dispatch(): 

319 raise asyncio.CancelledError() 

320 

321 async def _prepare(self, client: EntityClient): 

322 """Subscribe to client events and check that another operation is still permitted. 

323 

324 Callers must send their request before the next suspension to preserve this check. 

325 """ 

326 await client.subscribe_events() 

327 self._check_dispatch() 

328 

329 def pending(self) -> bool: 

330 """Return True while a tracked lifecycle task call is awaiting a result.""" 

331 return any(not call.future().done() for call in self._calls) 

332 

333 @staticmethod 

334 def _ended(call: TaskCall) -> bool: 

335 """Return whether a call's execution is known to have ended.""" 

336 return call.future().done() and isinstance(call.error(), TaskFailed | None) 

337 

338 async def run_task( 

339 self, 

340 task: Task, 

341 *, 

342 context: KeywordDict | None = None, 

343 timeout: float | None = None, 

344 ) -> ControllerState: 

345 """Execute and track a lifecycle task, interrupting any controller task in progress. 

346 

347 Outside recovery, the supervisor expects a transition from dispatch until it verifies 

348 the result. Any other outcome leaves the expected state unknown. 

349 

350 Args: 

351 task: The lifecycle task to execute. 

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

353 timeout: Seconds before the execution is aborted, or None to wait for its result. 

354 

355 Returns: 

356 The controller state read after the task succeeded. 

357 

358 Raises: 

359 ProcedureError: If the request is rejected. 

360 ControllerFailure: If the task fails, times out, or the controller state cannot be 

361 read afterward. 

362 ControllerIndeterminate: If the execution may still be running. 

363 """ 

364 controller = self.supervisor.controller 

365 await self._prepare(controller) 

366 

367 call = TaskCall(controller, task, context=context, interrupt=True) 

368 self._calls.append(call) 

369 

370 if self.expects_target: 

371 self.supervisor.expect_transition() 

372 

373 # Dispatch before yielding after the interruption check. 

374 # Keep waiting for acceptance if procedure logic is interrupted. 

375 sent = asyncio.eager_task_factory(asyncio.get_running_loop(), call.send()) 

376 sent.add_done_callback(cleanup_future) 

377 

378 try: 

379 # Read dispatch failures from the call's shared result below. 

380 with contextlib.suppress(CallRejected, TaskOutcomeUnknown): 

381 await asyncio.shield(sent) 

382 

383 if await interruptible_wait((call.future(),), timeout=timeout): 

384 call.abort() 

385 await interruptible_wait((call.future(),), timeout=self.abort_budget) 

386 

387 error = call.error() 

388 

389 # Remove resolved calls before raising their result to avoid duplicate cleanup errors. 

390 if call.future().done() and not isinstance(error, TaskOutcomeUnknown): 

391 self._calls.remove(call) 

392 

393 match error: 

394 case None if not call.future().done(): 

395 raise ControllerIndeterminate( 

396 f"{task.task_type} execution may still be running" 

397 ) 

398 case None if self.expects_target: 

399 return await self.confirm_state(task.target_state(), context, commanded=True) 

400 case None if (state := task.target_state()) is not None: 

401 return await self.supervisor.verify(state, context) 

402 case None: 

403 return await self.supervisor.refresh() 

404 case CallRejected(): 

405 raise ProcedureError(f"{task.task_type} task rejected") from error 

406 case TaskFailed(aborted=True): 

407 raise ControllerFailure(f"{task.task_type} task aborted") from error 

408 case TaskFailed(): 

409 raise ControllerFailure(f"{task.task_type} task failed") from error 

410 case _: 

411 raise ControllerIndeterminate( 

412 f"{task.task_type} execution may still be running" 

413 ) from error 

414 except BaseException: 

415 self.supervisor.invalidate() 

416 raise 

417 

418 async def run_unless_achieved(self, task: Task): 

419 """Run a lifecycle task unless the controller is known to be settled at its target state. 

420 

421 Both the state and demanded lifecycle context must match, with no transition pending. 

422 Matching controller state alone is not enough after a failure or an unconfirmed task. 

423 

424 Raises: 

425 ProcedureError: If the task request is rejected. 

426 ControllerFailure: If the task fails or the resulting state or context differs. 

427 ControllerIndeterminate: If the task cannot be confirmed stopped. 

428 """ 

429 state = task.target_state() 

430 context = self.demand.lifecycle_context() 

431 self._check_dispatch() 

432 

433 # Controllers should also skip work that is already done, but the agent does not rely on it. 

434 if self.supervisor.settled(state, context): 

435 await self.confirm_state(state, context, commanded=False) 

436 return 

437 

438 await self.run_task(task, context=context) 

439 

440 async def confirm_state( 

441 self, 

442 state: InternalControllerState, 

443 context: KeywordDict | None = None, 

444 *, 

445 commanded: bool, 

446 ) -> ControllerState: 

447 """Verify and record the required controller state and lifecycle context. 

448 

449 Args: 

450 state: The required state. 

451 context: The required lifecycle context, or None for an empty context. 

452 commanded: Whether this procedure's own lifecycle task established the state. 

453 """ 

454 snapshot = await self.supervisor.confirm(state, context) 

455 self.achieved = True 

456 self.commanded |= commanded 

457 return snapshot 

458 

459 @abstractmethod 

460 async def state_logic(self): 

461 """Run logic for this procedure.""" 

462 

463 async def stop_logic(self): 

464 """Perform graceful cleanup specific to this procedure. 

465 

466 Runs after tracked lifecycle tasks and registered futures finish. Overrides should stop 

467 any program tasking they started or adopted. Failure, timeout, or an abort request 

468 escalates to abort logic. 

469 """ 

470 

471 async def abort_logic(self): 

472 """Perform abort cleanup specific to this procedure. 

473 

474 Runs after aborting tracked lifecycle tasks and canceling registered futures. 

475 Overrides should abort any program tasking they started or adopted. 

476 """ 

477 

478 async def shield_with_cleanup[T](self, fut: asyncio.Future[T]) -> T: 

479 """Await a future while shielding it from interruption. 

480 

481 Graceful cleanup waits for the future, and abort cancels it. 

482 """ 

483 self._cleanup_futures.add(fut) 

484 result = await asyncio.shield(fut) 

485 self._cleanup_futures.discard(fut) 

486 return result 

487 

488 @final 

489 async def stop(self): 

490 """Request a graceful end and wait until cleanup has finished.""" 

491 self.request_stop() 

492 await self.join() 

493 

494 @final 

495 async def abort(self): 

496 """Request an immediate end and wait until cleanup has finished.""" 

497 self.request_abort() 

498 await self.join() 

499 

500 @final 

501 def cancel(self): 

502 """Cancel procedure logic and cleanup without sending further requests. 

503 

504 Work that has not ended remains unresolved. 

505 """ 

506 self.future().cancel() 

507 

508 @final 

509 async def join(self): 

510 """Wait for the procedure and cleanup without propagating their exceptions.""" 

511 await asyncio.wait((self.future(),)) 

512 

513 @final 

514 def done(self): 

515 """Return True if the procedure and its cleanup have finished.""" 

516 return self.future().done() 

517 

518 @final 

519 def error(self) -> BaseException | None: 

520 """Return the procedure's failure, or None if running, successful, or cancelled.""" 

521 task = self.future() 

522 

523 if not task.done() or task.cancelled(): 

524 return None 

525 

526 return task.exception() 

527 

528 @final 

529 def future(self) -> asyncio.Task[None]: 

530 """Return the procedure task for use as an awaitable or in `asyncio.wait`.""" 

531 assert self._task is not None, "procedure not started" 

532 return self._task 

533 

534 

535class OperateProcedure(LifecycleProcedure): 

536 """Achieve OPERATE and supervise program tasking. 

537 

538 Cleanup targets the session started or acknowledged by this procedure. 

539 Returning from state logic leaves tasking for the next procedure to adopt or abort. 

540 

541 Each procedure owns one tasking session. The session's first reported fault remains the 

542 procedure's failure through cleanup. 

543 """ 

544 

545 activation_timeout: ClassVar[float] = 5.0 

546 """Seconds to wait for program tasking to start.""" 

547 

548 def __init__(self, supervisor: ControllerStateSupervisor, demand: DemandState): 

549 super().__init__(supervisor, demand) 

550 self._activation: ProgramActivation | None = None 

551 self._ends_tasking = False 

552 

553 @override 

554 def _failure(self) -> BaseException | None: 

555 if (fault := self._tasking_fault()) is not None: 

556 return self._fault_error(fault) 

557 

558 return super()._failure() 

559 

560 @override 

561 async def state_logic(self): 

562 controller = str(self.supervisor.controller.entity) 

563 program = self.demand.program 

564 

565 self.step = LifecycleStep.INIT 

566 await self._reconcile_existing_tasking() 

567 

568 # Matching tasking has already been acknowledged by activation. 

569 adopted = self._activation is not None 

570 

571 logger.info(f"Preparing to operate ({controller})") 

572 await self.run_unless_achieved(InitTask()) 

573 

574 # Maintain OPERATE while waiting for a program demand. 

575 if program is None: 

576 self.step = LifecycleStep.WAIT 

577 logger.info(f"Waiting for a program for tasking ({controller})") 

578 await asyncio.sleep(float("inf")) 

579 

580 self.step = LifecycleStep.TASKING 

581 

582 if adopted: 

583 logger.info(f"Resuming {program.entity} tasking ({controller})") 

584 else: 

585 logger.info(f"Activating {program.entity} program ({controller})") 

586 await self.activate_tasking() 

587 

588 logger.info(f"Controller is operating ({controller})") 

589 

590 # Follow session faults, external stop requests, and program restarts. 

591 stop_event = await self._tasking_ended() 

592 

593 match stop_event.origin: 

594 case "error": 

595 # Unclassified legacy errors count toward controller recovery. 

596 logger.error(f"Error reported ({controller})") 

597 raise ControllerFailure("Program reported error") 

598 case "init": 

599 # TODO: Bound tasking retries after program restarts. 

600 logger.warning(f"Active program restarted ({controller})") 

601 

602 # Pause briefly, then return for replacement. 

603 self.step = LifecycleStep.WAIT 

604 await asyncio.sleep(3) 

605 case "request": 

606 logger.info(f"Tasking stopped by request ({controller})") 

607 raise ProcedureError("Program was stopped") 

608 

609 @override 

610 async def stop_logic(self): 

611 await self._end_tasking(abort=False) 

612 

613 @override 

614 async def abort_logic(self): 

615 try: 

616 await self._end_tasking(abort=True) 

617 finally: 

618 # A failed abort leaves no confirmation that program tasking stopped. 

619 self.unresolved |= self._ends_tasking 

620 

621 async def _end_tasking(self, *, abort: bool): 

622 """Wait for startup, then stop or abort the accepted session.""" 

623 activation = self._activation 

624 

625 if activation is None: 

626 return 

627 

628 try: 

629 await activation 

630 except Exception as e: 

631 self._classify_activation_failure(e) 

632 

633 try: 

634 if not self._ends_tasking: 

635 return 

636 

637 # Cleanup requires the identity returned by acceptance. 

638 if activation.monitor is None: 

639 self.unresolved = True 

640 return 

641 

642 program = self.demand.program 

643 end = program.abort_tasking if abort else program.stop_tasking 

644 await end(activation.monitor.session_id) 

645 self._ends_tasking = False 

646 finally: 

647 # Read any session fault preceding the cleanup reply. 

648 if activation.monitor is not None: 

649 activation.monitor.read_events() 

650 

651 @staticmethod 

652 def _fault_error(state: TaskingLoopState) -> ProcedureError: 

653 """Convert a session fault to a procedure failure.""" 

654 operation = state.stage if state.task_type is None else f"{state.task_type} {state.stage}" 

655 message = f"Tasking failed during {operation} ({state.error})" 

656 

657 match state.fault: 

658 case "controller": 

659 return ControllerFailure(message) 

660 case _: 

661 return ProcedureError(message) 

662 

663 def _tasking_fault(self) -> TaskingLoopState | None: 

664 """Return the owned session's first reported fault, if any.""" 

665 if self._activation is None or (monitor := self._activation.monitor) is None: 

666 return None 

667 

668 return monitor.fault 

669 

670 async def _tasking_ended(self) -> ProgramActiveState: 

671 """Wait for the owned session to end or report a fault. 

672 

673 Raises: 

674 ProcedureError: If the session reported a fault. 

675 """ 

676 monitor = self._activation.monitor 

677 await monitor.wait() 

678 

679 if (fault := monitor.fault) is not None: 

680 raise self._fault_error(fault) 

681 

682 return monitor.ending 

683 

684 async def _reconcile_existing_tasking(self): 

685 """Adopt the demanded program's active tasking, or abort it. 

686 

687 Adopt tasking only if its controller and task contexts match demand and the controller 

688 reports the required state and lifecycle context. Otherwise, abort the program's tasking. 

689 

690 Raises: 

691 ProcedureError: If existing tasking could not be acknowledged or ended. 

692 """ 

693 program = self.demand.program 

694 

695 if program is None: 

696 return 

697 

698 try: 

699 tasking = await program.kv_get_model(ProgramState) 

700 except KeyNotFound: 

701 return 

702 

703 if not tasking.active_state.active: 

704 return 

705 

706 enabled_on = tasking.enable_state.controller 

707 session = tasking.tasking_state.loop_state 

708 

709 if ( 

710 not tasking.active_state.stopping 

711 and (session is None or session.fault is None) 

712 and enabled_on is not None 

713 and Entity.at(enabled_on) == self.supervisor.controller.entity 

714 and tasking.active_state.contexts == (self.demand.contexts or TaskContextMap()) 

715 and self.supervisor.settled(self.demand.state, self.demand.lifecycle_context()) 

716 ): 

717 await self.activate_tasking(adopt=True) 

718 return 

719 

720 await self._prepare(program) 

721 

722 # Reconcile current tasking before taking responsibility for a session. 

723 try: 

724 async with asyncio.timeout(self.abort_budget): 

725 await program.abort_tasking() 

726 except Exception as e: 

727 raise ProcedureError(f"Could not abort {program.entity} tasking") from e 

728 

729 async def activate_tasking(self, *, adopt: bool = False): 

730 """Activate tasking and retain its identity for cleanup. 

731 

732 New activation clears running controller work first. Adoption preserves the matching 

733 session's execution. Cleanup waits for activation and targets its returned session ID. 

734 Uncertain acceptance or completion leaves tasking unresolved. 

735 

736 Args: 

737 adopt: Whether existing tasking already matches demand. 

738 

739 Raises: 

740 ControllerFailure: If a running execution could not be aborted. 

741 ProcedureError: If tasking did not start in time. 

742 """ 

743 program = self.demand.program 

744 controller = self.supervisor.controller 

745 

746 if self._activation is not None: 

747 raise RuntimeError("Tasking was already activated") 

748 

749 if not adopt and (execution := self.supervisor.running_execution()) is not None: 

750 await self._prepare(controller) 

751 

752 try: 

753 async with asyncio.timeout(self.abort_budget): 

754 await controller.abort_task(execution.task_id) 

755 except CallRejected: 

756 # The execution already ended. A later request is rejected if other work started. 

757 pass 

758 except Exception as e: 

759 raise ControllerFailure(f"Could not abort {execution.task.task_type} task") from e 

760 

761 activation = program.start_tasking(self.demand.contexts) 

762 

763 try: 

764 # Keep a sent start request alive for cleanup if activation times out. 

765 async with asyncio.timeout(self.activation_timeout) as deadline: 

766 await activation.prepare() 

767 

768 # Prevent dispatch if procedure cancellation is already pending. 

769 if self.future().cancelling(): 

770 raise asyncio.CancelledError() 

771 

772 # Recheck demand after preparation and send before yielding. 

773 self._check_dispatch() 

774 self._activation = activation 

775 self._ends_tasking = True 

776 self.future().add_done_callback(lambda _: activation.close()) 

777 await activation.send() 

778 except Exception as e: 

779 if deadline.expired(): 

780 raise ProcedureError("Tasking did not start in time") from e 

781 

782 cause = e if self._activation is None else self._classify_activation_failure(e) 

783 raise ProcedureError("Failed to start tasking") from cause 

784 finally: 

785 if self._activation is None: 

786 activation.close() 

787 

788 def _classify_activation_failure(self, error: Exception) -> Exception: 

789 """Classify an activation failure and update cleanup requirements.""" 

790 program = self.demand.program.entity 

791 

792 match error: 

793 case CallRejected(): 

794 # A rejected start needs no session cleanup. 

795 self._ends_tasking = False 

796 return error 

797 case TaskingStartupFailed(): 

798 # A failure response confirms that the start handler finished. 

799 return error 

800 case TaskingError(): 

801 message = f"{program} did not confirm tasking" 

802 case _: 

803 message = f"{program} may start tasking later" 

804 

805 self.unresolved = True 

806 indeterminate = ControllerIndeterminate(message) 

807 indeterminate.__cause__ = error 

808 return indeterminate 

809 

810 

811class StandbyProcedure(LifecycleProcedure): 

812 """Achieve STANDBY and wait for replacement.""" 

813 

814 @override 

815 async def state_logic(self): 

816 controller = str(self.supervisor.controller.entity) 

817 

818 self.step = LifecycleStep.STANDBY 

819 

820 logger.info(f"Entering standby mode ({controller})") 

821 await self.run_unless_achieved(StandbyTask()) 

822 

823 self.step = LifecycleStep.WAIT 

824 

825 logger.info(f"Controller is idle in standby ({controller})") 

826 await asyncio.sleep(float("inf")) 

827 

828 

829class ShutdownProcedure(LifecycleProcedure): 

830 """Achieve SHUTDOWN and wait for replacement.""" 

831 

832 @override 

833 async def state_logic(self): 

834 controller = str(self.supervisor.controller.entity) 

835 

836 self.step = LifecycleStep.SHUTDOWN 

837 

838 logger.info(f"Commencing shutdown ({controller})") 

839 await self.run_unless_achieved(ShutdownTask()) 

840 

841 self.step = LifecycleStep.WAIT 

842 

843 logger.info(f"Controller is shut down ({controller})") 

844 await asyncio.sleep(float("inf")) 

845 

846 

847class RecoverProcedure(LifecycleProcedure): 

848 """Run one recovery attempt, or an emergency shutdown once attempts are exhausted. 

849 

850 Recovery can start from and leave any reported state, so it leaves the expected state 

851 unknown. The reactor schedules attempts and evaluates demand again after each one. 

852 """ 

853 

854 expects_target = False 

855 

856 recover_timeout: ClassVar[float] = 120.0 

857 """Seconds before a recovery attempt is aborted.""" 

858 

859 shutdown_timeout: ClassVar[float] = 240.0 

860 """Seconds before an emergency shutdown is aborted.""" 

861 

862 def __init__( 

863 self, 

864 supervisor: ControllerStateSupervisor, 

865 demand: DemandState, 

866 *, 

867 emergency: bool, 

868 ): 

869 super().__init__(supervisor, demand) 

870 self.emergency = emergency 

871 """Whether this attempt is an emergency shutdown.""" 

872 self.recovered = False 

873 """Whether the recovery task succeeded.""" 

874 

875 @override 

876 async def state_logic(self): 

877 controller = str(self.supervisor.controller.entity) 

878 

879 if self.emergency: 

880 self.step = LifecycleStep.SHUTDOWN 

881 task = ShutdownTask() 

882 context = self.demand.lifecycle_context(task.target_state()) 

883 

884 logger.warning(f"Failed to recover, attempting shutdown ({controller})") 

885 await self.run_task(task, context=context, timeout=self.shutdown_timeout) 

886 

887 # Emergency shutdown leaves control disabled pending operator intervention. 

888 logger.info(f"Emergency shutdown succeeded ({controller})") 

889 raise ControllerUnrecoverable("Emergency shutdown") 

890 

891 self.step = LifecycleStep.RECOVER 

892 

893 logger.info(f"Attempting recovery ({controller})") 

894 await self.run_task(RecoverTask(), timeout=self.recover_timeout) 

895 

896 logger.info(f"Recovery succeeded ({controller})") 

897 self.recovered = True