Coverage for core / src / sensorkit / core / executor.py: 94%

443 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 

6from collections.abc import AsyncGenerator, Coroutine 

7from datetime import UTC, datetime, timedelta 

8from typing import Any, Callable 

9 

10import uuid_utils.compat as uuid 

11from loguru import logger 

12 

13from sensorkit.backend.request import Call, CallError, CallRejected 

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

15from sensorkit.common.keyword import KeywordDict 

16from sensorkit.core.controller import ( 

17 ControllerClient, 

18 ControllerMonitor, 

19 ExecuteResponseMessage, 

20 ExecutionStateStream, 

21 InternalControllerState, 

22 TaskExecutionResult, 

23 TaskExecutionState, 

24) 

25from sensorkit.core.entity import EventsNotSubscribed 

26from sensorkit.core.program import TaskingFault, TaskingLoopState, TaskingStage 

27from sensorkit.core.task import Task, TaskContextMap, TaskExecution, TaskSubmission 

28 

29type TaskFactoryResult = Task | TaskSubmission | None 

30type TaskFactoryFunc = Callable[ 

31 [], 

32 Coroutine[Any, Any, TaskFactoryResult] 

33 | AsyncGenerator[TaskFactoryResult, TaskExecution] 

34 | TaskFactoryResult, 

35] 

36type TaskingChangeCallback = Callable[ 

37 [TaskingLoopState, TaskExecutionState | None], Coroutine[Any, Any, None] 

38] 

39"""Receive session progress and the accepted execution's latest state event.""" 

40 

41 

42class NoTaskAvailable(Exception): 

43 """There is no task available for execution.""" 

44 

45 

46async def _invoke_factory( 

47 func: TaskFactoryFunc, 

48) -> tuple[AsyncGenerator[TaskFactoryResult, TaskExecution] | None, TaskSubmission]: 

49 """Invoke a task factory and normalize its output. 

50 

51 The factory may be a plain function or coroutine returning a `Task`/`TaskSubmission`/`None`, or 

52 an async generator that yields one of those and is later resumed with the minted 

53 `TaskExecution` (see `_resume_factory`). 

54 

55 Returns: 

56 A tuple of the generator to resume after dispatch (or `None` for non-generator factories) 

57 and the normalized `TaskSubmission`. 

58 

59 Raises: 

60 NoTaskAvailable: If the factory offers no task this cycle. 

61 """ 

62 obj = func() 

63 

64 match obj: 

65 case AsyncGenerator(): 

66 agen = obj 

67 try: 

68 result = await agen.asend(None) 

69 except StopAsyncIteration as e: 

70 # A generator that never yields is a no-task scenario rather than an error. 

71 raise NoTaskAvailable from e 

72 case Coroutine(): 

73 agen = None 

74 result = await obj 

75 case Task() | TaskSubmission() | None: 

76 agen = None 

77 result = obj 

78 case _: 

79 raise RuntimeError("task factory returned invalid type") 

80 

81 if result is None: 

82 # The factory had no task for us. Close any generator so its finally-blocks run. 

83 if agen is not None: 

84 await agen.aclose() 

85 

86 raise NoTaskAvailable 

87 

88 # Normalize a bare task into a submission with no execution parameters. 

89 submission = result if isinstance(result, TaskSubmission) else TaskSubmission(task=result) 

90 

91 return agen, submission 

92 

93 

94async def _resume_factory( 

95 agen: AsyncGenerator[TaskFactoryResult, TaskExecution], execution: TaskExecution 

96) -> None: 

97 """Resume a factory generator once, handing it the minted execution. 

98 

99 The generator may simply end (ignoring the result), or `await` the execution itself to consume 

100 the result before ending. Either way it is expected to stop after a single resumption. 

101 """ 

102 try: 

103 await agen.asend(execution) 

104 except StopAsyncIteration: 

105 # Expected: the factory ran its post-dispatch logic (if any) and ended. 

106 return 

107 else: 

108 logger.warning( 

109 "Task factory generator yielded more than once! This indicates a programming error." 

110 ) 

111 await agen.aclose() 

112 

113 

114class TaskOutcomeUnknown(Exception): 

115 """Task acceptance or execution completion could not be confirmed.""" 

116 

117 

118class TaskFailed(CallError): 

119 """A task execution ended without success.""" 

120 

121 def __init__(self, *args, aborted: bool = False): 

122 super().__init__(*args) 

123 self.aborted = aborted 

124 """Whether this call requested an abort before receiving the failed result.""" 

125 

126 

127class TaskCall: 

128 """Send one task to a controller and follow the execution it starts. 

129 

130 Rejection confirms that the task did not run. After acceptance, the execution's end event 

131 confirms success or failure. Missing acceptance or completion leaves the call unresolved. 

132 

133 An observing call streams state events for its execution until the call completes. 

134 """ 

135 

136 def __init__( 

137 self, 

138 controller: ControllerClient, 

139 task: Task, 

140 *, 

141 context: KeywordDict | None = None, 

142 expiry_time: datetime | None = None, 

143 interrupt: bool = False, 

144 observe: bool = False, 

145 ): 

146 """Create a call without sending it. 

147 

148 Args: 

149 controller: The controller to execute the task. 

150 task: The task to execute. 

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

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

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

154 observe: Whether to stream state events for the execution. 

155 """ 

156 self.controller = controller 

157 self.task = task 

158 self.context = context 

159 self.expiry_time = expiry_time 

160 self.interrupt = interrupt 

161 self.observe = observe 

162 self.execution: TaskExecution | None = None 

163 """The execution the controller identified, if any.""" 

164 loop = asyncio.get_running_loop() 

165 self._outcome: asyncio.Future[TaskExecutionResult] = loop.create_future() 

166 self._outcome.add_done_callback(cleanup_future) 

167 self._abort = asyncio.Event() 

168 self._sent = False 

169 self._follower: asyncio.Task[TaskExecutionResult] | None = None 

170 self._states: ExecutionStateStream | None = None 

171 

172 async def send(self) -> TaskExecution: 

173 """Send the request and wait until the controller accepts the task. 

174 

175 The request goes out before the caller first suspends. Canceling the caller while it 

176 waits for the reply leaves the call unresolved. The returned execution can be awaited 

177 for the call's result. 

178 

179 Raises: 

180 RuntimeError: If the call was already sent. 

181 EventsNotSubscribed: If the controller's events are not subscribed. 

182 BackendError: If the controller's event subscription failed to start. 

183 CallRejected: If the controller rejected the task without running it. 

184 TaskOutcomeUnknown: If acceptance could not be established. 

185 """ 

186 if self._sent: 

187 raise RuntimeError("Task call already sent") 

188 

189 mux = self.controller.get_event_mux() 

190 

191 if not mux.ready(): 

192 raise EventsNotSubscribed(f"{self.controller.entity} events are not subscribed") 

193 

194 self._sent = True 

195 

196 if self.observe: 

197 # Buffer state events until acceptance identifies the execution. 

198 self._states = ExecutionStateStream(self.controller) 

199 

200 call = self.controller.execute_task( 

201 self.task, context=self.context, expiry_time=self.expiry_time, interrupt=self.interrupt 

202 ) 

203 

204 try: 

205 await call.invoke() 

206 except CallRejected as e: 

207 # A rejection reply can still identify the execution it declined. 

208 if call.response is not None: 

209 self._identify(call.response.execution) 

210 

211 self._settle_outcome(error=e) 

212 raise 

213 except asyncio.CancelledError as e: 

214 # Losing the reply leaves acceptance unknown even if the controller started the task. 

215 self._settle_outcome(error=self._outcome_unknown("acceptance is unknown", e)) 

216 raise 

217 except Exception as e: 

218 error = self._outcome_unknown("acceptance is unknown", e) 

219 self._settle_outcome(error=error) 

220 raise error from e 

221 

222 if call.response is None or call.response.execution is None: 

223 error = self._outcome_unknown("was accepted without an execution") 

224 self._settle_outcome(error=error) 

225 raise error 

226 

227 execution = call.response.execution 

228 self._identify(execution) 

229 

230 # Holders of the execution await the outcome without canceling it. 

231 shared = asyncio.shield(self._outcome) 

232 shared.add_done_callback(cleanup_future) 

233 execution.bind_result(shared) 

234 

235 self._follower = asyncio.create_task(self._follow(call, execution)) 

236 self._follower.add_done_callback(self._settle) 

237 

238 return execution 

239 

240 def execution_states(self) -> ExecutionStateStream: 

241 """Return the state event stream for the identified execution. 

242 

243 Iteration ends once the call completes and buffered events are consumed. 

244 

245 Raises: 

246 RuntimeError: If the call does not observe execution states or was not sent. 

247 """ 

248 if self._states is None: 

249 raise RuntimeError("Task call does not observe execution states") 

250 

251 return self._states 

252 

253 def _identify(self, execution: TaskExecution | None): 

254 self.execution = execution 

255 

256 if execution is not None and self._states is not None: 

257 self._states.bind(execution) 

258 

259 def _settle_outcome( 

260 self, result: TaskExecutionResult | None = None, *, error: BaseException | None = None 

261 ): 

262 """Release state observation and complete the result future.""" 

263 # Keep buffered state events available after completing the result future. 

264 if self._states is not None: 

265 self._states.close() 

266 

267 if self._outcome.done(): 

268 return 

269 

270 if error is not None: 

271 self._outcome.set_exception(error) 

272 else: 

273 self._outcome.set_result(result) 

274 

275 def abort(self): 

276 """Request an abort of the execution once the controller accepts it. 

277 

278 Repeated requests retry a failed abort until the controller accepts one. 

279 The execution's end event determines the result. 

280 """ 

281 self._abort.set() 

282 

283 def future(self) -> asyncio.Future[TaskExecutionResult]: 

284 """Return the shared future for task rejection or the execution result. 

285 

286 The future raises `CallRejected` if the task never ran, `TaskFailed` if the execution 

287 ended without success, and `TaskOutcomeUnknown` if acceptance or completion is unknown. 

288 Use `asyncio.wait` or `asyncio.shield` to keep waiter cancellation from canceling it. 

289 """ 

290 return self._outcome 

291 

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

293 """Return why the call ended without success, or None if running or successful.""" 

294 if not self._outcome.done(): 

295 return None 

296 

297 if self._outcome.cancelled(): 

298 return self._outcome_unknown("outcome was cancelled") 

299 

300 return self._outcome.exception() 

301 

302 def _outcome_unknown(self, reason: str, cause: BaseException | None = None) -> TaskOutcomeUnknown: 

303 error = TaskOutcomeUnknown(f"{self.task.task_type} {reason}") 

304 error.__cause__ = cause 

305 return error 

306 

307 def _settle(self, follower: asyncio.Task[TaskExecutionResult]): 

308 if follower.cancelled(): 

309 self._settle_outcome(error=self._outcome_unknown("call was cancelled")) 

310 elif (error := follower.exception()) is not None: 

311 self._settle_outcome(error=error) 

312 else: 

313 self._settle_outcome(follower.result()) 

314 

315 async def _follow( 

316 self, 

317 call: Call[ExecuteResponseMessage, TaskExecutionResult], 

318 execution: TaskExecution, 

319 ) -> TaskExecutionResult: 

320 result = call.get_future() 

321 aborted = False 

322 delivered = False 

323 

324 while not result.done(): 

325 if not await interruptible_wait((result,), interrupt=self._abort): 

326 break 

327 

328 # Requests received during this send trigger another attempt if the send fails. 

329 self._abort.clear() 

330 aborted = True 

331 

332 if not delivered: 

333 delivered = await self._send_abort(execution) 

334 

335 error = asyncio.CancelledError() if result.cancelled() else result.exception() 

336 

337 match error: 

338 case None: 

339 return result.result() 

340 case CallError(): 

341 outcome = "aborted" if aborted else "failed" 

342 raise TaskFailed(f"{self.task.task_type} {outcome}", aborted=aborted) from error 

343 case _: 

344 # The end event was lost, so the execution may still be running. 

345 raise self._outcome_unknown("end is unknown", error) 

346 

347 async def _send_abort(self, execution: TaskExecution) -> bool: 

348 """Send a targeted abort and return whether the controller accepted it.""" 

349 try: 

350 await self.controller.abort_task(execution.task_id).invoke() 

351 except Exception as e: 

352 logger.warning(f"Could not abort {self.task.task_type} execution ({e!r})") 

353 return False 

354 

355 return True 

356 

357 

358class TaskingLoop: 

359 """Produce tasks while a controller reports OPERATE. 

360 

361 Each loop owns one session and its final task call. Faults end task production and 

362 retain their origin and failed stage through cleanup. 

363 """ 

364 

365 def __init__( 

366 self, 

367 controller: ControllerClient, 

368 factory_func: TaskFactoryFunc, 

369 contexts: TaskContextMap, 

370 task_group: asyncio.TaskGroup, 

371 *, 

372 on_tasking_change: TaskingChangeCallback | None = None, 

373 overrides: KeywordDict | None = None, 

374 ): 

375 self.controller = controller 

376 self.task_factory: TaskFactoryFunc = factory_func 

377 self.contexts = contexts 

378 self.overrides = KeywordDict(overrides) 

379 """Keywords added to every submitted task, replacing factory and config values.""" 

380 self._task_group = task_group 

381 self._on_tasking_change = on_tasking_change 

382 self.loop_state = TaskingLoopState(session_id=uuid.uuid7(), stage="factory") 

383 """Current operation and any terminal fault.""" 

384 self.execution_state: TaskExecutionState | None = None 

385 """Latest controller report for this session's execution.""" 

386 self._published: tuple[TaskingLoopState, TaskExecutionState | None] | None = None 

387 self._publication_lock = asyncio.Lock() 

388 self._monitor = ControllerMonitor(controller) 

389 self._aio_task: asyncio.Task | None = None 

390 self._stop_requested = asyncio.Event() 

391 self.finalized = False 

392 """Whether task production ended and the last call returned a result or error.""" 

393 self.unresolved = False 

394 """Whether the last call could not confirm task acceptance or completion.""" 

395 self._call: TaskCall | None = None 

396 self._publisher: asyncio.Task[None] | None = None 

397 self._finalization: asyncio.Task | None = None 

398 

399 def start(self): 

400 """Activate the tasking loop.""" 

401 if self._aio_task is not None or self.finalized: 

402 raise RuntimeError("Tasking loop was already started") 

403 

404 self._aio_task = self._task_group.create_task(self._run()) 

405 return self._aio_task 

406 

407 async def finalize(self): 

408 """Wait for the producer and last task call, preserving them if the caller is canceled.""" 

409 await asyncio.shield(self._finalizing()) 

410 

411 def _finalizing(self) -> asyncio.Task[None]: 

412 """Return the shared finalization task, starting it if needed.""" 

413 if self._finalization is None: 

414 self._finalization = asyncio.create_task(self._finalize()) 

415 self._finalization.add_done_callback(cleanup_future) 

416 

417 return self._finalization 

418 

419 @property 

420 def running(self) -> bool: 

421 """Whether the task producer is running and no stop has been requested.""" 

422 return not self._producer_done() and not self._stop_requested.is_set() 

423 

424 @property 

425 def stop_requested(self): 

426 """Return True if a stop has been requested for this tasking loop.""" 

427 return self._stop_requested.is_set() 

428 

429 def request_stop(self, *, abort: bool = False): 

430 """Stop producing tasks, optionally canceling the factory and aborting the current task.""" 

431 # Record cleanup intent before canceling work. 

432 self._stop_requested.set() 

433 

434 if abort: 

435 self._end_work() 

436 

437 def _end_work(self): 

438 """Cancel task production and request an execution abort.""" 

439 self._cancel_producer() 

440 

441 if self._call is not None: 

442 self._call.abort() 

443 

444 def _producer_done(self) -> bool: 

445 return self._aio_task is None or self._aio_task.done() 

446 

447 def _cancel_producer(self): 

448 if self._aio_task is not None and not self._aio_task.cancelling(): 

449 self._aio_task.cancel() 

450 

451 def _advance(self, stage: TaskingStage, task_type: str | None = None): 

452 """Change the current operation while the session is healthy.""" 

453 if self.loop_state.fault is None: 

454 self.loop_state = TaskingLoopState( 

455 session_id=self.loop_state.session_id, stage=stage, task_type=task_type 

456 ) 

457 

458 def _fail( 

459 self, 

460 fault: TaskingFault, 

461 error: BaseException | str, 

462 *, 

463 stage: TaskingStage | None = None, 

464 ): 

465 """Retain the first fault ending this session.""" 

466 state = self.loop_state 

467 

468 if isinstance(error, BaseException): 

469 error = f"{type(error).__name__}: {error}" 

470 

471 if state.fault is not None: 

472 logger.warning(f"Tasking {self.controller.entity} also failed ({error})") 

473 return 

474 

475 stage = state.stage if stage is None else stage 

476 logger.error(f"Tasking {self.controller.entity} failed during {stage} ({error})") 

477 

478 self.loop_state = TaskingLoopState( 

479 session_id=state.session_id, 

480 stage=stage, 

481 task_type=state.task_type, 

482 fault=fault, 

483 error=error, 

484 ) 

485 

486 def _classify(self, call: TaskCall): 

487 """Classify a failed controller call. 

488 

489 Requested aborts retain the session's existing outcome. 

490 """ 

491 if self.loop_state.fault is not None: 

492 return 

493 

494 match error := call.error(): 

495 case None | TaskFailed(aborted=True): 

496 return 

497 case CallRejected(): 

498 self._fail("controller", error, stage="dispatch") 

499 case TaskOutcomeUnknown() if call.execution is None: 

500 self._fail("controller", error, stage="dispatch") 

501 case _: 

502 self._fail("controller", error, stage="execution") 

503 

504 async def _publish_tasking_state(self): 

505 """Publish changes to session progress and execution state.""" 

506 if self._on_tasking_change is None: 

507 return 

508 

509 async with self._publication_lock: 

510 snapshot = (self.loop_state, self.execution_state) 

511 

512 if snapshot == self._published: 

513 return 

514 

515 try: 

516 await self._on_tasking_change(*snapshot) 

517 except Exception as e: 

518 logger.opt(exception=e).warning( 

519 f"Could not report {self.controller.entity} tasking" 

520 ) 

521 else: 

522 self._published = snapshot 

523 

524 def _resolve_context(self, submission: TaskSubmission) -> KeywordDict | None: 

525 """Merge the factory context, the per-task-type context bundle, and the overrides.""" 

526 context = KeywordDict(submission.context or {}) 

527 

528 if type_context := self.contexts.get(submission.task.task_type): 

529 context.update(type_context) 

530 

531 context.update(self.overrides) 

532 

533 return context or None 

534 

535 def _resolve_expiry(self, submission: TaskSubmission) -> datetime | None: 

536 """Resolve the absolute expiry time for a submission. 

537 

538 Uses the factory-supplied `expiry_time` when present, otherwise the task's 

539 `default_expiry`. A `timedelta` default is anchored to the current time. 

540 """ 

541 if submission.expiry_time is not None: 

542 return submission.expiry_time 

543 

544 default = submission.task.default_expiry() 

545 

546 if isinstance(default, timedelta): 

547 return datetime.now(UTC) + default 

548 

549 return default 

550 

551 async def _run(self): 

552 # Publish session identity before task production. 

553 await self._publish_tasking_state() 

554 

555 try: 

556 await self._supervised() 

557 except Exception as e: 

558 self._fail("program", e) 

559 finally: 

560 try: 

561 await self._monitor.stop() 

562 except Exception as e: 

563 logger.opt(exception=e).warning( 

564 f"{self.controller.entity} observation release failed" 

565 ) 

566 

567 async def _supervised(self): 

568 """Run task production under controller observation.""" 

569 try: 

570 # Subscribe before starting calls that depend on execution events. 

571 await self.controller.subscribe_events() 

572 await self._monitor.start() 

573 current = self._monitor.operating_state.current 

574 except Exception as e: 

575 self._fail("controller", e) 

576 return 

577 

578 if current != InternalControllerState.OPERATE: 

579 self._fail("controller", f"{self.controller.entity} reported {current}") 

580 return 

581 

582 with self._monitor.state_changes(initial_value=False) as changes: 

583 supervisor = asyncio.create_task(self._supervise(changes)) 

584 

585 try: 

586 await self._produce() 

587 finally: 

588 supervisor.cancel() 

589 await asyncio.wait((supervisor,)) 

590 

591 async def _supervise(self, changes: asyncio.Queue): 

592 """End task production if the controller leaves OPERATE.""" 

593 while True: 

594 try: 

595 current = (await changes.get()).current 

596 except asyncio.QueueShutDown: 

597 error = f"{self.controller.entity} observation ended ({self._monitor.error!r})" 

598 break 

599 

600 if current != InternalControllerState.OPERATE: 

601 error = f"{self.controller.entity} reported {current}" 

602 break 

603 

604 # Ignore departures caused by requested cleanup. 

605 if self._stop_requested.is_set(): 

606 return 

607 

608 self._fail("controller", error) 

609 self._end_work() 

610 await asyncio.shield(self._publish_tasking_state()) 

611 

612 async def _produce(self): 

613 while not self._stop_requested.is_set(): 

614 # Clear the previous execution before starting another factory attempt. 

615 self.execution_state = None 

616 self._advance("factory") 

617 await self._publish_tasking_state() 

618 

619 try: 

620 agen, submission = await _invoke_factory(self.task_factory) 

621 except NoTaskAvailable: 

622 with contextlib.suppress(TimeoutError): 

623 await asyncio.wait_for(self._stop_requested.wait(), timeout=5.0) 

624 

625 continue 

626 except Exception as e: 

627 self._fail("program", e) 

628 return 

629 

630 # The producer owns cleanup, even if the factory yields after an injected exception. 

631 try: 

632 if self._stop_requested.is_set(): 

633 await self._throw(agen, asyncio.CancelledError()) 

634 return 

635 

636 # Continue task production only after successful dispatch and handling. 

637 if not await self._dispatch(agen, submission): 

638 return 

639 except Exception as e: 

640 # Record the fault before cleanup can be interrupted. 

641 self._fail("program", e) 

642 return 

643 finally: 

644 try: 

645 if agen is not None: 

646 await agen.aclose() 

647 except Exception as error: 

648 logger.warning( 

649 f"Task factory cleanup failed for {self.controller.entity} ({error!r})" 

650 ) 

651 

652 async def _dispatch( 

653 self, 

654 agen: AsyncGenerator[TaskFactoryResult, TaskExecution] | None, 

655 submission: TaskSubmission, 

656 ) -> bool: 

657 """Execute one factory submission and its program handling. 

658 

659 Returns: 

660 Whether execution and program handling completed successfully. 

661 """ 

662 task = submission.task 

663 context = self._resolve_context(submission) 

664 expiry_time = self._resolve_expiry(submission) 

665 ttl = (expiry_time - datetime.now(UTC)).total_seconds() if expiry_time else None 

666 

667 self._advance("dispatch", task.task_type) 

668 await self._publish_tasking_state() 

669 

670 logger.info( 

671 f"Dispatching {task.task_type} ({type(task).__name__}) to {self.controller.entity}" 

672 ) 

673 

674 call = TaskCall( 

675 self.controller, task, context=context, expiry_time=expiry_time, observe=True 

676 ) 

677 self._call = call 

678 

679 # Deliver dispatch errors to the suspended factory so its error handling and cleanup run. 

680 try: 

681 # Preserve acceptance so cancellation can abort the specific execution that started. 

682 execution = await defer_cancellation(call.send()) 

683 except asyncio.CancelledError as e: 

684 # Interrupted tasking aborts the execution once the controller accepts it. 

685 call.abort() 

686 self._publish_execution(call) 

687 await self._throw(agen, e) 

688 return False 

689 except Exception as e: 

690 self._fail("controller", e) 

691 self._publish_execution(call) 

692 await self._publish_tasking_state() 

693 await self._throw(agen, e) 

694 return False 

695 

696 publisher = self._publish_execution(call) 

697 

698 try: 

699 async with asyncio.timeout(ttl) as deadline: 

700 # Resumed generator code can run before execution ends. 

701 if agen is not None: 

702 self._advance("post_task", task.task_type) 

703 await self._publish_tasking_state() 

704 resumed, agen = agen, None 

705 await _resume_factory(resumed, execution) 

706 

707 if not call.future().done(): 

708 self._advance("execution", task.task_type) 

709 await self._publish_tasking_state() 

710 await asyncio.shield(call.future()) 

711 except (Exception, asyncio.CancelledError) as e: 

712 logger.opt(exception=e).debug(f"Tasking ended during {execution.task_id}") 

713 self._end_task(call, e, expired=deadline.expired()) 

714 await self._publish_tasking_state() 

715 await self._throw(agen, e) 

716 return False 

717 

718 # Check the execution outcome independently of generator handling. 

719 await asyncio.wait((publisher,)) 

720 

721 if self.loop_state.fault is not None: 

722 return False 

723 

724 self._call = None 

725 self._publisher = None 

726 logger.info(f"Finished {task.task_type} ({type(task).__name__})") 

727 

728 return True 

729 

730 def _end_task(self, call: TaskCall, error: BaseException, *, expired: bool): 

731 """Record a terminal fault before aborting the execution.""" 

732 # Classify established execution failure before program handling errors. 

733 self._classify(call) 

734 

735 match error: 

736 case _ if expired and not call.future().done(): 

737 self._fail("controller", f"{call.task.task_type} expired", stage="execution") 

738 case asyncio.CancelledError(): 

739 # Cleanup preserves any fault already recorded. 

740 pass 

741 case _ if error is call.error(): 

742 pass 

743 case _: 

744 self._fail("program", error) 

745 

746 call.abort() 

747 

748 def _publish_execution(self, call: TaskCall) -> asyncio.Task[None] | None: 

749 """Start publishing state events for the accepted execution.""" 

750 if call.execution is None: 

751 return None 

752 

753 self._publisher = asyncio.create_task(self._publish_execution_states(call)) 

754 self._publisher.add_done_callback(cleanup_future) 

755 

756 return self._publisher 

757 

758 async def _publish_execution_states(self, call: TaskCall): 

759 """Publish execution state changes and any terminal controller fault.""" 

760 async for state in call.execution_states(): 

761 self.execution_state = state 

762 await self._publish_tasking_state() 

763 

764 await asyncio.wait((call.future(),)) 

765 self._classify(call) 

766 await self._publish_tasking_state() 

767 

768 async def _throw( 

769 self, agen: AsyncGenerator[TaskFactoryResult, TaskExecution] | None, e: BaseException 

770 ): 

771 """Resume a suspended factory with an exception.""" 

772 if agen is None: 

773 return 

774 

775 try: 

776 await agen.athrow(e) 

777 except Exception as error: 

778 # Keep factory cleanup errors as secondary diagnostics. 

779 if error is not e and not isinstance(error, StopAsyncIteration): 

780 logger.warning( 

781 f"Task factory cleanup failed for {self.controller.entity} ({error!r})" 

782 ) 

783 except BaseException: 

784 pass 

785 

786 async def _finalize(self): 

787 if self._aio_task is not None: 

788 await asyncio.wait((self._aio_task,)) 

789 

790 # The producer can exit while its last controller task is still running. 

791 if (call := self._call) is not None: 

792 await asyncio.wait((call.future(),)) 

793 self.unresolved = isinstance(call.error(), TaskOutcomeUnknown) 

794 

795 if self._publisher is not None: 

796 await asyncio.wait((self._publisher,)) 

797 

798 # Retry fault publication interrupted by cancellation. 

799 await self._publish_tasking_state() 

800 

801 self._call = None 

802 self._publisher = None 

803 self.finalized = True