Coverage for core / src / sensorkit / core / program.py: 95%

423 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 collections 

6import contextlib 

7import functools 

8from abc import abstractmethod 

9from collections.abc import AsyncIterator, Generator 

10from datetime import datetime 

11from typing import TYPE_CHECKING, Any, Callable, Literal 

12 

13import uuid_utils.compat as uuid 

14from intervaltree import Interval 

15from loguru import logger 

16from pydantic import BaseModel, Field, model_validator 

17 

18from sensorkit.backend.base import KeyNotFound 

19from sensorkit.backend.event import Event 

20from sensorkit.backend.request import CallError, declare_long_request, declare_request 

21from sensorkit.common.aio import AsyncObserver, cleanup_future 

22from sensorkit.common.keyword import declare_keyword 

23from sensorkit.core.controller import TaskExecutionState 

24from sensorkit.core.entity import EntityClient, EntityInterface, EntityRef 

25from sensorkit.core.task import TaskContextMap 

26 

27if TYPE_CHECKING: 

28 from sensorkit.core.client import SensorKit 

29 from sensorkit.core.executor import TaskFactoryFunc 

30 

31type TaskingStage = Literal["factory", "dispatch", "execution", "post_task"] 

32"""Operations within a tasking session.""" 

33 

34type TaskingFault = Literal["controller", "program"] 

35"""Fault origins for program tasking.""" 

36 

37 

38class OfferInterval(Interval): 

39 """An Interval subclass with typed begin/end datetimes used to represent a program offer window.""" 

40 

41 begin: datetime 

42 end: datetime 

43 data: Any = None 

44 

45 

46@declare_keyword 

47class ProgramOffering(BaseModel): 

48 """Keyword publishing the set of offer windows during which this program can task a controller.""" 

49 

50 offer_windows: list[OfferInterval] 

51 

52 

53@declare_keyword(key="Program") 

54class ProgramInfo(BaseModel): 

55 """Keyword identifying the program that submitted a task.""" 

56 

57 id: str 

58 

59 def get_fits_cards(self): 

60 yield "SKPROG", (self.id, "SensorKit program name") 

61 

62 

63class ProgramEnableState(Event): 

64 """Event indicating the Program enable state has changed.""" 

65 enabled: bool = False 

66 controller: str | None = None 

67 

68 

69class ProgramActiveState(Event): 

70 """Event indicating the Program active state has changed.""" 

71 active: bool 

72 origin: Literal["request", "init", "error"] 

73 stopping: bool = False 

74 contexts: TaskContextMap = Field(default_factory=TaskContextMap) 

75 

76 

77class TaskingLoopState(BaseModel): 

78 """Current operation and terminal fault for a tasking session. 

79 

80 A fault retains the failed stage while the session ends. 

81 """ 

82 

83 session_id: uuid.UUID 

84 stage: TaskingStage 

85 task_type: str | None = None 

86 """Task type supplied by the factory.""" 

87 fault: TaskingFault | None = None 

88 error: str | None = None 

89 

90 

91class ProgramTaskingState(Event): 

92 """Program session progress and controller execution reports.""" 

93 

94 loop_state: TaskingLoopState | None = None 

95 """Known tasking session, if any.""" 

96 execution_state: TaskExecutionState | None = None 

97 """Controller report for the accepted execution. 

98 

99 Cleared before each factory attempt and retained when the session ends. 

100 """ 

101 

102 @model_validator(mode="before") 

103 @classmethod 

104 def _migrate_legacy_executing_task(cls, data: Any) -> Any: 

105 """Normalize legacy tasking reports. 

106 

107 Full executions retain their reported running state. Bare task IDs provide no 

108 execution state. Legacy reports carry no session identity. 

109 """ 

110 if not isinstance(data, dict) or not {"executing_task", "executing_task_id"} & data.keys(): 

111 return data 

112 

113 legacy = data.get("executing_task") 

114 data = {k: v for k, v in data.items() if k not in ("executing_task", "executing_task_id")} 

115 

116 if legacy is not None and "execution_state" not in data: 

117 data["execution_state"] = {"executing": True, "execution": legacy} 

118 

119 return data 

120 

121 

122class ProgramState(BaseModel): 

123 """Internal state snapshot of a Program.""" 

124 enable_state: ProgramEnableState 

125 active_state: ProgramActiveState 

126 tasking_state: ProgramTaskingState 

127 

128 @model_validator(mode="before") 

129 @classmethod 

130 def _migrate_legacy_tasking_state(cls, data: Any) -> Any: 

131 """Upgrade KV snapshots persisted before `tasking_status` was renamed to `tasking_state`. 

132 

133 Versions predating the Task/TaskExecution split stored the program's executing task under a 

134 `tasking_status` key (a `ProgramTaskingStatus` carrying `executing_task_id`); this 

135 version expects `tasking_state`. Renaming the key here lets `ProgramTaskingState`'s own 

136 `before` validator finish upgrading the inner shape, so a program starting against a NATS 

137 broker holding older state no longer raises a `ValidationError`. A snapshot missing both 

138 keys entirely is treated as idle. 

139 """ 

140 if not isinstance(data, dict) or "tasking_state" in data: 

141 return data 

142 

143 data = dict(data) 

144 data["tasking_state"] = data.pop("tasking_status", {}) 

145 return data 

146 

147 

148class ProgramEnableStateRequest(BaseModel): 

149 """Request that a Program enable or disable task sourcing. 

150 

151 The `controller` field specifies the name of the target Controller to task. It must be 

152 specified before activating the Program, and some Program implementations may require that it 

153 be specified whenever `enable` is True. 

154 """ 

155 enable: bool 

156 controller: str | None 

157 

158 

159set_enable_state_request = declare_request( 

160 "set_enable_state", 

161 message=ProgramEnableStateRequest, 

162) 

163"""Control the enable state of a Program.""" 

164 

165 

166class ProgramActiveStateRequest(BaseModel): 

167 """Request that a Program activate or deactivate tasking of the target Controller.""" 

168 action: Literal["start", "stop", "abort"] 

169 contexts: TaskContextMap = Field(default_factory=TaskContextMap) 

170 session_id: uuid.UUID | None = None 

171 """Target session for stop or abort, or None for the current session. 

172 

173 An ended target succeeds without affecting a later session. 

174 """ 

175 

176 def active_state(self): 

177 """Return True if the requested action is 'start', False otherwise.""" 

178 return True if self.action == "start" else False 

179 

180 

181class ProgramActiveStateResponse(BaseModel): 

182 """Session selected by a successful start acceptance.""" 

183 

184 session_id: uuid.UUID 

185 

186 

187set_active_state_request = declare_long_request( 

188 "set_active_state", 

189 message=ProgramActiveStateRequest, 

190 response=ProgramActiveStateResponse, 

191) 

192"""Control the active state of a Program.""" 

193 

194 

195class TaskingError(Exception): 

196 """Program tasking startup failed or could not be confirmed.""" 

197 

198 def __init__(self, *args, session_id: uuid.UUID): 

199 super().__init__(*args) 

200 self.session_id = session_id 

201 """Server-selected session.""" 

202 

203 

204class TaskingStartupFailed(TaskingError): 

205 """The program explicitly returned a startup failure for an accepted session.""" 

206 

207 

208class ProgramTaskingMonitor: 

209 """Observe progress and retain the outcome of one program tasking session. 

210 

211 Ordered program tasking events associate untagged events with their preceding session. 

212 The selected session's fault and ending remain available after its live report is cleared. 

213 

214 Construction starts buffering events. Bind to the accepted session before consuming them. 

215 Use a context manager or close the monitor to release observation. 

216 """ 

217 

218 def __init__(self, program: ProgramClient): 

219 """Buffer program events before reading initial state or starting tasking. 

220 

221 Args: 

222 program: Program with an active event subscription. 

223 """ 

224 self._session_id: uuid.UUID | None = None 

225 self.loop_state: TaskingLoopState | None = None 

226 """Latest progress with the first session fault retained.""" 

227 self.execution_state: TaskExecutionState | None = None 

228 """Controller report for the selected session's execution.""" 

229 self.ending: ProgramActiveState | None = None 

230 """Inactive event ending the selected session.""" 

231 self._subscription = program.get_event_mux().subscribe( 

232 ProgramTaskingState, ProgramActiveState 

233 ) 

234 self._current: uuid.UUID | None = None 

235 self._current_after = 0 

236 

237 def bind(self, session_id: uuid.UUID, initial: ProgramState | None = None): 

238 """Select a session and seed observation before processing buffered events. 

239 

240 Args: 

241 session_id: Session identified by the program. 

242 initial: Program state observed before starting tasking. 

243 

244 Raises: 

245 RuntimeError: If the monitor is already bound. 

246 """ 

247 if self._session_id is not None: 

248 raise RuntimeError("Program tasking monitor is already bound") 

249 

250 self._session_id = session_id 

251 

252 if initial is not None: 

253 self._observe(initial.tasking_state) 

254 

255 @property 

256 def session_id(self) -> uuid.UUID: 

257 """The selected session. 

258 

259 Raises: 

260 RuntimeError: If the monitor is not bound. 

261 """ 

262 if self._session_id is None: 

263 raise RuntimeError("Program tasking monitor is not bound") 

264 

265 return self._session_id 

266 

267 @property 

268 def fault(self) -> TaskingLoopState | None: 

269 """Retained terminal fault, if reported.""" 

270 state = self.loop_state 

271 return state if state is not None and state.fault is not None else None 

272 

273 def read_events(self) -> list[ProgramTaskingState]: 

274 """Process buffered events and return the selected session's tasking states. 

275 

276 Raises: 

277 RuntimeError: If the monitor is not bound. 

278 """ 

279 if self._session_id is None: 

280 raise RuntimeError("Program tasking monitor is not bound") 

281 

282 states = [] 

283 

284 for event in self._subscription.drain(): 

285 if (state := self._observe(event)) is not None: 

286 states.append(state) 

287 

288 return states 

289 

290 async def events(self) -> AsyncIterator[ProgramTaskingState]: 

291 """Yield selected-session tasking states until a fault or ending is observed. 

292 

293 Consume with one iterator or waiter at a time. Cancellation leaves unread events 

294 available for cleanup. Initial snapshot state is not yielded. 

295 

296 Raises: 

297 RuntimeError: If the monitor is not bound. 

298 QueueShutDown: If observation closes before a session outcome is known. 

299 """ 

300 if self._session_id is None: 

301 raise RuntimeError("Program tasking monitor is not bound") 

302 

303 if self.fault is not None or self.ending is not None: 

304 return 

305 

306 async for event in self._subscription: 

307 if (state := self._observe(event)) is not None: 

308 yield state 

309 

310 if self.fault is not None or self.ending is not None: 

311 return 

312 

313 raise asyncio.QueueShutDown("Program tasking monitor closed before its outcome") 

314 

315 async def wait(self): 

316 """Wait for a session fault or ending. 

317 

318 Cancellation leaves unread events available for cleanup. 

319 

320 Raises: 

321 RuntimeError: If the monitor is not bound. 

322 QueueShutDown: If the monitor is closed first. 

323 """ 

324 async for _ in self.events(): 

325 pass 

326 

327 def close(self): 

328 """Close observation and wake pending waiters.""" 

329 self._subscription.close() 

330 

331 def __enter__(self): 

332 return self 

333 

334 def __exit__(self, *_): 

335 self.close() 

336 

337 def _observe(self, event: Event) -> ProgramTaskingState | None: 

338 """Update the selected session from one ordered event.""" 

339 if self.ending is not None: 

340 return 

341 

342 match event: 

343 case ProgramTaskingState(loop_state=TaskingLoopState() as state): 

344 self._current = state.session_id 

345 self._current_after = event.event_id.int 

346 

347 if state.session_id == self.session_id: 

348 self._report(state, event.execution_state) 

349 return event 

350 case ProgramTaskingState() if ( 

351 self._current == self.session_id and event.event_id.int > self._current_after 

352 ): 

353 # Keep the final execution report after the live session clears. 

354 self.execution_state = event.execution_state 

355 return event 

356 case ProgramActiveState(active=True, stopping=False) if ( 

357 event.event_id.int > self._current_after 

358 ): 

359 # The next report identifies the newly active session. 

360 self._current = None 

361 self._current_after = event.event_id.int 

362 case ProgramActiveState(active=False) if ( 

363 self._current == self.session_id and event.event_id.int > self._current_after 

364 ): 

365 self.ending = event 

366 

367 def _report(self, state: TaskingLoopState, execution_state: TaskExecutionState | None): 

368 if self.fault is None: 

369 self.loop_state = state 

370 

371 self.execution_state = execution_state 

372 

373 

374class ProgramActivation: 

375 """Start program tasking or reuse a matching active session. 

376 

377 Await this object to prepare and send the start request, then receive the session 

378 monitor after startup is confirmed. Repeated sends and awaits use the same request. 

379 

380 Call `prepare()` before checking conditions that must hold at dispatch. 

381 Once prepared, `send()` sends the request before its first suspension. 

382 """ 

383 

384 def __init__(self, program: ProgramClient, contexts: TaskContextMap): 

385 """Create an activation without subscribing or sending a request. 

386 

387 Args: 

388 program: The program to activate. 

389 contexts: Task contexts supplied to the program. 

390 """ 

391 self.program = program 

392 self.contexts = contexts 

393 self.monitor: ProgramTaskingMonitor | None = None 

394 """The accepted session's monitor, retained if startup fails or cannot be confirmed.""" 

395 self._monitor: ProgramTaskingMonitor | None = None 

396 self._initial: ProgramState | None = None 

397 self._prepared = False 

398 self._start: asyncio.Task[ProgramTaskingMonitor] | None = None 

399 

400 async def prepare(self): 

401 """Subscribe to program events and read state without sending the start request. 

402 

403 If preparation fails or is canceled, it releases its subscription and can be retried. 

404 

405 Raises: 

406 RuntimeError: If preparation is already in progress. 

407 """ 

408 if self._prepared: 

409 return 

410 

411 if self._monitor is not None: 

412 raise RuntimeError("Activation is already preparing") 

413 

414 await self.program.subscribe_events() 

415 self._monitor = ProgramTaskingMonitor(self.program) 

416 

417 try: 

418 # Buffer events received while reading state and starting tasking. 

419 with contextlib.suppress(KeyNotFound): 

420 self._initial = await self.program.kv_get_model(ProgramState) 

421 except BaseException: 

422 self._monitor.close() 

423 self._monitor = None 

424 raise 

425 

426 self._prepared = True 

427 

428 async def send(self) -> ProgramTaskingMonitor: 

429 """Send the start request and return the session monitor after startup is confirmed. 

430 

431 Preparation runs automatically if needed. Canceling a waiter leaves the request 

432 running. The caller must close the monitor when observation ends. 

433 

434 Raises: 

435 CallRejected: If the program rejects activation. 

436 TaskingStartupFailed: If the program explicitly returns a startup failure. 

437 TaskingError: If startup cannot be confirmed after acceptance. 

438 CallError: If the acceptance response omits the session ID. 

439 """ 

440 if self._start is None: 

441 # A prepared request goes out before this call first suspends. 

442 self._start = asyncio.eager_task_factory( 

443 asyncio.get_running_loop(), self._send_start_request() 

444 ) 

445 self._start.add_done_callback(cleanup_future) 

446 

447 return await asyncio.shield(self._start) 

448 

449 def __await__(self) -> Generator[Any, None, ProgramTaskingMonitor]: 

450 return self.send().__await__() 

451 

452 def close(self): 

453 """Release the event subscription without stopping program tasking.""" 

454 if self._monitor is not None: 

455 self._monitor.close() 

456 

457 async def _send_start_request(self) -> ProgramTaskingMonitor: 

458 await self.prepare() 

459 

460 call = self.program.call( 

461 set_active_state_request, 

462 ProgramActiveStateRequest(action="start", contexts=self.contexts), 

463 ) 

464 

465 try: 

466 response = await call.invoke() 

467 

468 if response is None: 

469 raise CallError(f"{self.program.entity} accepted tasking without a session") 

470 except BaseException: 

471 self._monitor.close() 

472 raise 

473 

474 self._monitor.bind(response.session_id, self._initial) 

475 self.monitor = self._monitor 

476 

477 try: 

478 await call 

479 except CallError as e: 

480 raise TaskingStartupFailed( 

481 f"{self.program.entity} failed to start tasking ({e})", 

482 session_id=response.session_id, 

483 ) from e 

484 except Exception as e: 

485 raise TaskingError( 

486 f"{self.program.entity} did not confirm tasking ({e})", 

487 session_id=response.session_id, 

488 ) from e 

489 

490 return self.monitor 

491 

492 

493class ProgramClient(EntityClient): 

494 """Object that exposes client-side functionality of a Program.""" 

495 

496 async def enable(self, target_controller: str): 

497 """Request that the Program enable task sourcing for the target Controller.""" 

498 return await self.call( 

499 set_enable_state_request, 

500 ProgramEnableStateRequest( 

501 enable=True, 

502 controller=target_controller, 

503 ) 

504 ) 

505 

506 async def disable(self): 

507 """Request that the Program disable task sourcing.""" 

508 return await self.call( 

509 set_enable_state_request, 

510 ProgramEnableStateRequest( 

511 enable=False, 

512 controller=None, 

513 ) 

514 ) 

515 

516 def start_tasking(self, contexts: TaskContextMap | None = None) -> ProgramActivation: 

517 """Create an awaitable request to start or reuse program tasking. 

518 

519 Await it to receive the accepted session's monitor after startup is confirmed. 

520 A matching active session keeps its identity and current execution. 

521 

522 Args: 

523 contexts: Task contexts supplied to the program. 

524 """ 

525 return ProgramActivation(self, contexts or TaskContextMap()) 

526 

527 async def stop_tasking(self, session_id: uuid.UUID | None = None): 

528 """Stop producing tasks and wait for the program's current controller task to end. 

529 

530 Args: 

531 session_id: The session to stop, or None for the current session. 

532 

533 Raises: 

534 CallError: If the program cannot confirm that its controller task ended. 

535 """ 

536 await self.call( 

537 set_active_state_request, 

538 ProgramActiveStateRequest(action="stop", session_id=session_id), 

539 ) 

540 

541 async def abort_tasking(self, session_id: uuid.UUID | None = None): 

542 """Stop producing tasks, abort the program's current controller task, and await its end. 

543 

544 Args: 

545 session_id: The session to abort, or None for the current session. 

546 

547 Raises: 

548 CallError: If the program cannot confirm that its controller task ended. 

549 """ 

550 await self.call( 

551 set_active_state_request, 

552 ProgramActiveStateRequest(action="abort", session_id=session_id), 

553 ) 

554 

555 async def wait_until_tasking_stops(self): 

556 """ 

557 Wait until the Program tasking loop stops. 

558 

559 Returns the corresponding ProgramActiveState event, if any. 

560 """ 

561 # TODO: This needs to detect if the hosting service goes down and raise if it doesn't 

562 # come back and publish new state within a grace period. 

563 stream = await self.tasking_change_events() 

564 state = await self.kv_get_model(ProgramState) 

565 

566 if state.active_state.active: 

567 async for event in stream: 

568 if not event.active: 

569 return event 

570 

571 return None 

572 

573 def tasking_change_events(self): 

574 """Return an async generator that yields ProgramActiveState events as tasking starts or stops.""" 

575 return self.monitor_event(ProgramActiveState) 

576 

577 @functools.cache 

578 def monitor_enable_state(self): 

579 """Return (creating if needed) a ProgramStateMonitor tracking this program's enable state.""" 

580 monitor = ProgramStateMonitor(self) 

581 monitor.start() 

582 return monitor 

583 

584 

585class ProgramRef(EntityRef[ProgramClient]): 

586 """A serializable reference to a program client.""" 

587 

588 def _get_client(self, kit: SensorKit) -> ProgramClient: 

589 return kit.program(self.name) 

590 

591 

592class ControllerOffers: 

593 """Monitor published offers for all Programs associated with a Controller.""" 

594 

595 def __init__(self, controller: str, program_discovery: ProgramDiscovery): 

596 self.controller = controller 

597 self.program_discovery = program_discovery 

598 self._monitors: dict[str, asyncio.Task] = {} 

599 self._offers: dict[str, list[OfferInterval]] = {} 

600 

601 async def start(self, *, task_group: Any = asyncio): 

602 """Start the program-offer discovery loop, waiting until the first update is received.""" 

603 self._task_group = task_group 

604 

605 # Begin discovering controller offers, making sure to wait for the first set of updates. 

606 ready = asyncio.Event() 

607 self._discover_task = task_group.create_task(self._discover_programs(ready)) 

608 await ready.wait() 

609 

610 async def _discover_programs(self, initial_update: asyncio.Event): 

611 prev = set() 

612 

613 async for programs in self.program_discovery.controller_programs(self.controller): 

614 events = [] 

615 

616 for remove in prev.difference(programs): 

617 self._monitors[remove].cancel() 

618 del self._monitors[remove] 

619 

620 for add in programs.difference(prev): 

621 assert add not in self._monitors 

622 events.append(asyncio.Event()) 

623 self._monitors[add] = self._task_group.create_task( 

624 self._monitor_program(add, events[-1]) 

625 ) 

626 

627 await asyncio.gather(*(event.wait() for event in events), return_exceptions=True) 

628 initial_update.set() 

629 prev = programs 

630 

631 async def _monitor_program(self, program: str, initial_update: asyncio.Event): 

632 logger.debug(f"starting offer monitor for program {program}") 

633 self._offers[program] = [] 

634 

635 try: 

636 # Suppress propagation of cancellation to the parent task group. 

637 with contextlib.suppress(asyncio.CancelledError): 

638 # Get a stream of offers for the target Program. 

639 client = self.program_discovery.client.program(program) 

640 stream = await client.monitor(ProgramOffering) 

641 

642 initial_update.set() 

643 

644 async for _, offering in stream: 

645 self._offers[program] = sorted(offering.offer_windows) 

646 finally: 

647 initial_update.set() 

648 del self._offers[program] 

649 logger.debug(f"cancelled offer monitor for program {program}") 

650 

651 def get_offers(self): 

652 """Return a snapshot of the current offer windows keyed by program name. 

653 

654 Each program's offer windows are sorted in ascending order. 

655 """ 

656 return self._offers.copy() 

657 

658 

659class ProgramDiscovery: 

660 """Discover Programs and their associated Controllers.""" 

661 

662 def __init__(self): 

663 self._enabled_programs: AsyncObserver[frozenset[str]] = AsyncObserver(frozenset()) 

664 self._known_programs: AsyncObserver[frozenset[str]] = AsyncObserver(frozenset()) 

665 self._controllers: dict[str, AsyncObserver[frozenset[str]]] = collections.defaultdict( 

666 lambda: AsyncObserver(frozenset()) 

667 ) 

668 self._monitor_tasks: dict[str, asyncio.Task] = {} 

669 self._discover_task: asyncio.Task | None = None 

670 

671 async def start(self, client: SensorKit): 

672 """Begin monitoring the backend for program enable-state changes, waiting for the first update.""" 

673 self.client = client 

674 

675 # Begin discovering enabled programs, making sure to wait for the first set of updates. 

676 ready = asyncio.Event() 

677 self._discover_task = asyncio.create_task(self._discover_programs(ready)) 

678 await ready.wait() 

679 

680 async def stop(self): 

681 """Cancel discovery and every per-program enable-state monitor it started.""" 

682 if self._discover_task is None: 

683 return 

684 

685 self._discover_task.cancel() 

686 

687 for task in self._monitor_tasks.values(): 

688 task.cancel() 

689 

690 await asyncio.gather( 

691 self._discover_task, *self._monitor_tasks.values(), return_exceptions=True 

692 ) 

693 

694 self._monitor_tasks.clear() 

695 self._discover_task = None 

696 

697 async def _discover_programs(self, initial_update: asyncio.Event): 

698 tasks = self._monitor_tasks 

699 kv = self.client.backend.key_value() 

700 

701 # Programs present in the initial snapshot. We're "ready" once each of them 

702 # has been discovered and reported its initial enable state — or immediately 

703 # if there are none. 

704 pending = { 

705 str(entry.key.entity()) 

706 for entry in await kv.get_all(deep=True) 

707 if entry.key.prop == "ProgramState" 

708 } 

709 if not pending: 

710 initial_update.set() 

711 

712 # Monitor all registered Programs. 

713 # FIXME: Need an alternate way to do this without firehose. Cannot assume the backend 

714 # allows prefix wildcards to capture '*.ProgramState' (and NATS, in fact, does not). 

715 # This most likely means we need to define a dedicated KV prefix for system info, 

716 # where we can define keys to explicitly indicate existence, like EntityLease. 

717 monitor = await kv.monitor_all(deep=True) 

718 

719 async for entry in monitor: 

720 if entry.key.prop != "ProgramState": 

721 continue 

722 

723 program = str(entry.key.entity()) 

724 client = self.client.program(program) 

725 events = [] 

726 

727 if entry.deleted(): 

728 # Remove the monitor task associated with the offline program, if any. 

729 if program in tasks: 

730 task = tasks.pop(program) 

731 task.cancel() 

732 self._known_programs.notify(frozenset(tasks.keys())) 

733 elif program not in tasks: 

734 # Start a new enable state monitor for the newly discovered program. 

735 events.append(asyncio.Event()) 

736 tasks[program] = asyncio.create_task(self._monitor_task(client, events[-1])) 

737 self._known_programs.notify(frozenset(tasks.keys())) 

738 

739 # Wait for the initial enablement status of each discovered program. 

740 await asyncio.gather(*(event.wait() for event in events), return_exceptions=True) 

741 

742 # Signal ready once every program from the initial snapshot has been seen. 

743 pending.discard(program) 

744 if not pending: 

745 initial_update.set() 

746 

747 async def _monitor_task(self, client: ProgramClient, initial_update: asyncio.Event): 

748 monitor = client.monitor_enable_state() 

749 program = str(client.entity) 

750 

751 try: 

752 async for state in monitor.observe(): 

753 observers = [self._enabled_programs] 

754 logger.debug(f"discovery for {program} observed {state=}") 

755 

756 if state: 

757 observers.append(self._controllers[state.controller]) 

758 

759 for observer in observers: 

760 if state and state.enabled: 

761 new_set = observer.value.union({program}) 

762 else: 

763 new_set = observer.value.difference({program}) 

764 

765 observer.notify(new_set) 

766 

767 initial_update.set() 

768 finally: 

769 monitor.stop() 

770 

771 def enabled_programs(self): 

772 """Return an async generator yielding the current set of enabled program names on each change.""" 

773 return self._enabled_programs.consume(initial_value=True) 

774 

775 def known_programs(self): 

776 """Return an async generator yielding the current set of all known program names on each change.""" 

777 return self._known_programs.consume(initial_value=True) 

778 

779 def controller_programs(self, controller: str): 

780 """Return an async generator yielding the set of programs targeting the given controller on each change.""" 

781 return self._controllers[controller].consume(initial_value=True) 

782 

783 

784class ProgramStateMonitor: 

785 """Monitor a Program's effective enable-state, taking into account the entity liveness.""" 

786 

787 def __init__(self, client: ProgramClient): 

788 self.client = client 

789 self.online = False 

790 self.enable_state: ProgramEnableState | None = None 

791 self._observer: AsyncObserver[ProgramEnableState | None] = AsyncObserver(None) 

792 

793 def start(self): 

794 """Start background tasks that monitor program liveness and enable-state.""" 

795 self._tasks = ( 

796 asyncio.create_task(self._monitor_liveness()), 

797 asyncio.create_task(self._monitor_state()), 

798 ) 

799 

800 def stop(self): 

801 """Cancel the background monitoring tasks.""" 

802 for t in self._tasks: 

803 t.cancel() 

804 

805 def observe(self): 

806 """Return an async generator yielding the current ProgramEnableState (or None if offline) on each change.""" 

807 return self._observer.consume(initial_value=True) 

808 

809 def _notify(self): 

810 if not self.online: 

811 self._observer.notify(None) 

812 else: 

813 self._observer.notify(self.enable_state) 

814 

815 async def _monitor_liveness(self): 

816 async for is_online in self.client.observe_online_state(): 

817 self.online = is_online 

818 self._notify() 

819 

820 async def _monitor_state(self): 

821 program = str(self.client.entity) 

822 

823 try: 

824 stream = await self.client.monitor_event(ProgramEnableState) 

825 initial_state = await self.client.kv_get_model(ProgramState) 

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

827 logger.debug(f"Failed to monitor program {program}: {e}") 

828 raise 

829 

830 logger.debug(f"monitoring discovered program {program}") 

831 self.enable_state = initial_state.enable_state 

832 self._notify() 

833 

834 async for event in stream: 

835 if event.timestamp() > self.enable_state.timestamp(): 

836 self.enable_state = event 

837 self._notify() 

838 

839 

840class ProgramInterface(EntityInterface): 

841 """Interface describing an implementation of a program.""" 

842 

843 @abstractmethod 

844 def on_enable(self, func: Callable[[], None]): 

845 """Register a callback to invoke when the program is enabled.""" 

846 ... 

847 

848 @abstractmethod 

849 def on_disable(self, func: Callable[[], None]): 

850 """Register a callback to invoke when the program is disabled.""" 

851 ... 

852 

853 @abstractmethod 

854 def task_factory(self, func: TaskFactoryFunc) -> TaskFactoryFunc: 

855 """Register the task factory function that the program calls to generate tasks. 

856 

857 Raises: 

858 RuntimeError: If the program already has a task factory. 

859 """ 

860 ... 

861 

862 @abstractmethod 

863 def get_offers(self) -> list[Any]: 

864 """Return the current list of offer windows.""" 

865 ... 

866 

867 @abstractmethod 

868 async def publish_offers(self): 

869 """Publish the current offer windows to the entity's keyword stream.""" 

870 ... 

871 

872 @abstractmethod 

873 def add_offer(self, start: datetime, end: datetime, obj: Any = None): 

874 """Add an offer window covering the given time range.""" 

875 ... 

876 

877 @abstractmethod 

878 def remove_offer(self, start: datetime, end: datetime, obj: Any = None): 

879 """Remove the offer window covering the given time range.""" 

880 ... 

881 

882 @abstractmethod 

883 def clear_offers(self): 

884 """Remove all offer windows.""" 

885 ...