Coverage for core / src / sensorkit / auto / operator.py: 88%
251 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2from __future__ import annotations
4import asyncio
5import contextlib
6import os
7from collections.abc import Iterable
8from datetime import UTC, datetime, timedelta
9from typing import Any
11from loguru import logger
12from pydantic import BaseModel, Field
14from sensorkit.astro.common import SitePosition
15from sensorkit.astro.observer import EarthObserver
16from sensorkit.auto.constraint import Constraint, ConstraintManager
17from sensorkit.auto.lifecycle import ControllerLifecycle
18from sensorkit.auto.mode import Mode, ModeList
19from sensorkit.auto.scheduler import ProgramConfig, Scheduler, debug_print_schedule
20from sensorkit.backend.base import KeyNotFound
21from sensorkit.common.aio import AsyncObserver
22from sensorkit.common.graph import StateElection
23from sensorkit.core.client import SensorKit
24from sensorkit.core.controller import InternalControllerState
25from sensorkit.core.program import ControllerOffers, ProgramClient, ProgramDiscovery, ProgramState
26from sensorkit.core.task import TaskContextMap, TaskContextOverlay
29class ControllerConfig(BaseModel):
30 """Configuration for a single Controller managed by the VirtualOperator."""
31 depends_on: list[str] = Field(default_factory=list)
32 estimated_startup_time: float = 0.0
33 estimated_shutdown_time: float = 0.0
34 transition_grace: float = Field(default=10.0, gt=0.0)
35 """Maximum seconds of state mismatch during a commanded lifecycle transition.
37 Time in TRANSITION does not count toward this limit.
38 """
39 modes: ModeList = Field(default_factory=list)
40 constraints: list[Constraint] = Field(default_factory=list)
41 tasking: list[ProgramConfig] = Field(default_factory=list)
42 contexts: TaskContextOverlay = Field(default_factory=TaskContextOverlay)
44 _name: str | None = None
45 _mode_index: dict[str, Mode]
46 _program_index: dict[str, ProgramConfig]
48 @property
49 def name(self):
50 """The name of this controller, set by the parent ControllerConfigMap validator."""
51 if self._name is None:
52 raise RuntimeError("name not set")
54 return self._name
56 @name.setter
57 def name(self, value: str):
58 """Set the name of this controller."""
59 self._name = value
61 def mode(self, name: str):
62 """Return the Mode configuration with the given name."""
63 return self._mode_index[name]
65 def program_config(self, program: str):
66 """Return the ProgramConfig for the given program entity name."""
67 return self._program_index[program]
69 def model_post_init(self, __context: Any):
70 self._mode_index = {mode.name: mode for mode in self.modes}
71 self._program_index = {config.program: config for config in self.tasking}
73 def propagate_config(self, contexts: TaskContextOverlay):
74 """Merge agent-level task contexts into this controller and its program configs."""
75 contexts.propagate(self.contexts)
77 for config in self.tasking:
78 self.contexts.propagate(config.contexts)
81class ControllerDriver:
82 """Operate a single Controller."""
84 def __init__(
85 self,
86 config: ControllerConfig,
87 program_discovery: ProgramDiscovery,
88 program_manager: ProgramStateManager,
89 ):
90 self.config = config
91 self.program_manager = program_manager
93 # Build task context maps. These are user-configured context keywords passed through
94 # to program tasking and direct task executions.
95 self._context_maps: dict[str | None, TaskContextMap] = {
96 None: config.contexts.build(),
97 **{cfg.program: cfg.contexts.build() for cfg in config.tasking},
98 }
100 # Create the Controller task offers monitor.
101 self.controller_offers = ControllerOffers(config.name, program_discovery)
103 # Create a scheduler.
104 self.scheduler = Scheduler(
105 modes=config.modes,
106 program_configs=config.tasking,
107 )
109 # Create constraint manager.
110 self.constraints = ConstraintManager(config.constraints)
112 # Create the lifecycle object.
113 self.lifecycle = ControllerLifecycle(transition_grace=config.transition_grace)
115 async def start(
116 self,
117 kit: SensorKit,
118 *,
119 task_group: Any = asyncio,
120 ):
121 """Start the lifecycle, constraints, offers monitor, and background tasks for this driver."""
122 self.kit = kit
123 controller = kit.controller(self.config.name)
124 logger.info(f"Driver for {self.config.name} starting")
126 # Start the lifecycle loop. This won't result in commanding until the lifecycle is enabled
127 # and a demand state is set.
128 self.lifecycle.start(controller, task_group=task_group)
130 # Start checking the configured constraints.
131 await self.constraints.start(task_group=task_group, ready_timeout=10.0, kit=kit)
133 # Start monitoring associated Programs for offers.
134 await self.controller_offers.start(task_group=task_group)
136 # Query controller site position.
137 while True:
138 try:
139 site = await controller.kv_get_model(SitePosition)
140 break
141 except KeyNotFound:
142 logger.debug(f"waiting for {self.config.name} SitePosition")
143 await asyncio.sleep(1)
145 self.observer = await EarthObserver.get(
146 lat_deg=site.latitude_degrees, lon_deg=site.longitude_degrees
147 )
149 logger.debug(f"driver for {self.config.name} ready")
151 async def stop(self):
152 """Stop the lifecycle and all background tasks for this driver."""
153 await self.lifecycle.stop()
155 def evaluate_state(self, election: StateElection):
156 """Update the schedule and cast election votes for schedule and constraints."""
157 # Build mode evaluation context.
158 mode_context = {
159 "time_range_parsers": {
160 "sunrise": self.observer.get_sunrise_time,
161 "sunset": self.observer.get_sunset_time,
162 },
163 }
165 # Update the schedule.
166 # FIXME: We do the full call twice here to ensure `tasking_available` and `after_activity`
167 # criteria pick up changes in a single iteration. This double-evaluation should be
168 # done more efficiently within the Scheduler itself.
169 for _ in range(2):
170 self.scheduler.update(
171 offers_dict=self.controller_offers.get_offers(),
172 enabled_programs=self.program_manager.enabled_programs(),
173 mode_context=mode_context,
174 )
176 if os.getenv("AGENT_DEBUG_SCHEDULE", None):
177 debug_print_schedule(self.scheduler, print_func=logger.debug)
179 # Check the schedule. Lookahead by startup time.
180 now = datetime.now(UTC)
181 intent = self.scheduler.get_intent(now)
182 if not intent and self.config.estimated_startup_time:
183 lookahead = now + timedelta(seconds=self.config.estimated_startup_time)
184 intent = self.scheduler.get_intent(lookahead)
186 election.vote(
187 "schedule",
188 subject=self.config.name,
189 vote=True if intent else None,
190 )
192 # Check constraints.
193 election.vote(
194 "constraint",
195 subject=self.config.name,
196 vote=False if self.constraints.is_constrained() else None,
197 )
199 def set_demand(self, operate: bool):
200 """Apply the elected operate/shutdown demand to the lifecycle, returning True if changed."""
201 state: InternalControllerState = InternalControllerState.SHUTDOWN
202 program: ProgramClient | None = None
204 if operate:
205 # Determine the target state (operate or standby) and which program to use, if any. If
206 # the controller's scheduler has something in mind, its intended state and program are
207 # used.
208 intent = self.scheduler.get_intent(datetime.now(UTC))
210 match intent and self.config.mode(intent.mode).state:
211 case "operate":
212 state = InternalControllerState.OPERATE
214 # Always use the highest-priority program given by the scheduler. Note that
215 # things like offline programs, temporary failure cooldowns, and other program
216 # availability constraints are already accounted for in the schedule. Any
217 # exclusions or re-prioritization here would not be visible in the published
218 # schedule, thus should be avoided. The full listing of candidate programs
219 # exists only for user informational purposes.
220 program = self.kit.program(intent.programs[0]) if intent.programs else None
221 case "standby":
222 state = InternalControllerState.STANDBY
223 case None:
224 # We are not scheduled to operate, so this must be a forced override scenario.
225 # Presently overrides alone cannot specify STANDBY.
226 state = InternalControllerState.OPERATE
227 case _ as it:
228 logger.error(
229 f"Invalid demand state {it!r} for mode {intent.mode}; "
230 "defaulting to SHUTDOWN"
231 )
232 state = InternalControllerState.SHUTDOWN
234 # Check constraints and determine appropriate contexts, whether we should interrupt. The
235 # contexts are a dict of dicts, mapping task types to the combined user configuration that
236 # applies for that task for this controller and program (if any).
237 constrained = self.constraints.is_constrained()
238 contexts = self._context_maps[None]
239 interrupt = False
240 program_interrupt = False
242 if constrained:
243 if state != InternalControllerState.SHUTDOWN:
244 # Refuse to go up if a constraint is active. This can happen if a constraint goes
245 # high between schedule updates. Note this is not redundant to the wiring of
246 # constraints through the StateElection, since the latter informs multi-controller
247 # dependencies and general observability.
248 state = InternalControllerState.SHUTDOWN
250 interrupt = True
251 program = None
253 if program:
254 program_name = str(program.entity)
255 program_config = self.config.program_config(program_name)
257 # The lifecycle defers program interruption until OPERATE with no pending lifecycle task.
258 contexts = self._context_maps[program_name]
259 program_interrupt = program_config.interrupt
261 changed = self.lifecycle.set_demand_state(
262 state,
263 contexts=contexts,
264 program=program,
265 interrupt=interrupt,
266 program_interrupt=program_interrupt,
267 )
269 if changed:
270 logger.debug(
271 f"{self.config.name} -> {str(state)} program={program.entity if program else None}"
272 )
274 return changed
277class ProgramStateManager:
278 """Manages the desired enable state for programs and drives remote state."""
280 def __init__(self, programs: Iterable[str]):
281 self.all_programs = frozenset(programs)
282 self._desired_enable: dict[
283 str, str | None
284 ] = {} # program -> target_controller or None if disabled
285 self._global_enabled = True
286 self.on_change = AsyncObserver[str | None](None)
287 self._controller: dict[str, list[str]] = {}
289 def assign_controller(self, program: str, controller: str | None = None):
290 """Register a controller as a candidate for a program."""
291 if program not in self._controller:
292 self._controller[program] = []
293 if controller not in self._controller[program]:
294 self._controller[program].append(controller)
296 async def enable(self, program: str):
297 """Mark *program* as enabled for its first registered candidate controller."""
298 candidates = self._controller.get(program, [])
299 if not candidates:
300 return
301 target = candidates[0]
302 current = self._desired_enable.get(program)
304 if current and current != target:
305 raise RuntimeError(f"Program {program} already enabled for {current}")
307 if current == target:
308 return
310 self._desired_enable[program] = target
311 self.on_change.notify(program)
313 async def disable(self, program: str):
314 """Mark *program* as disabled, removing it from the enabled set."""
315 if self._desired_enable.get(program) is not None:
316 del self._desired_enable[program]
317 self.on_change.notify(program)
319 async def global_enable(self):
320 """Enable the global scheduling gate, allowing all individually-enabled programs to run."""
321 if not self._global_enabled:
322 self._global_enabled = True
323 self.on_change.notify(None)
325 async def global_disable(self):
326 """Disable the global scheduling gate, preventing all programs from running."""
327 if self._global_enabled:
328 self._global_enabled = False
329 self.on_change.notify(None)
331 def is_enabled(self, program: str) -> bool:
332 """Return True if *program* is individually enabled and the global gate is open."""
333 return self._global_enabled and self._desired_enable.get(program) is not None
335 def get_target_controller(self, program: str) -> str | None:
336 """Return the target controller entity name for *program*, or None if disabled."""
337 if not self._global_enabled:
338 return None
339 return self._desired_enable.get(program)
341 async def start(
342 self,
343 client: SensorKit,
344 discovery: ProgramDiscovery,
345 task_group: asyncio.TaskGroup,
346 ):
347 """Start the background task that drives remote program enable/disable state."""
348 self.client = client
349 self.discovery = discovery
350 self._retries = set()
351 self._program_locks: dict[str, asyncio.Lock] = {}
353 # Start monitoring tasks.
354 task_group.create_task(self._watch_discovery())
355 task_group.create_task(self._watch_changes())
357 async def _handle_program(self, program: str):
358 if program not in self._program_locks:
359 self._program_locks[program] = asyncio.Lock()
361 async with self._program_locks[program]:
362 program_client = self.client.program(program)
364 try:
365 state = await program_client.kv_get_model(ProgramState)
366 target = self.get_target_controller(program)
368 if target:
369 if not state.enable_state.enabled or state.enable_state.controller != target:
370 logger.info(f"Enabling program {program} for {target}")
371 await program_client.enable(target)
372 else:
373 if state.enable_state.enabled:
374 logger.info(f"Disabling program {program}")
375 await program_client.disable()
376 except Exception as e:
377 logger.error(f"Failed to drive program {program} state: {e}")
379 async def delayed_retry(delay: float = 10.0):
380 logger.debug(f"retrying in {delay} sec")
381 await asyncio.sleep(delay)
382 await self._handle_program(program)
384 self._retries.add(asyncio.create_task(delayed_retry()))
386 for task in list(self._retries):
387 if task.done():
388 self._retries.discard(task)
390 async def _watch_discovery(self):
391 previous_discovered = set()
393 async for programs in self.discovery.known_programs():
394 changed = programs.symmetric_difference(previous_discovered)
396 for p in changed:
397 if p in self.all_programs:
398 await self._handle_program(p)
400 previous_discovered = programs
402 async def _watch_changes(self):
403 async for program in self.on_change.consume(initial_value=True):
404 if program is None:
405 # Global change, re-evaluate all programs.
406 for p in self.all_programs:
407 await self._handle_program(p)
408 else:
409 await self._handle_program(program)
411 def enabled_programs(self):
412 """Return the set of currently enabled program entity names."""
413 return set(self._desired_enable.keys()) if self._global_enabled else set()
416class VirtualOperator:
417 """Orchestrate a set of Controllers."""
419 def __init__(self, controllers: Iterable[ControllerConfig]):
420 # Create the state election object. This election is the final say on whether a Controller
421 # operates or not. It unites operating schedule determined from mode configuration and
422 # program offerings, constraint evaluation, dependency relationships, and overrides.
423 self.election = StateElection({config.name: config.depends_on for config in controllers})
425 # Create a discovery object to find Programs and their target Controllers.
426 self.discovery = ProgramDiscovery()
428 # Create a manager to handle program enablement.
429 self.programs = ProgramStateManager(
430 tasking.program for config in controllers for tasking in config.tasking
431 )
433 for ctrl in controllers:
434 for prog in ctrl.tasking:
435 self.programs.assign_controller(prog.program, ctrl.name)
437 # Create objects to operate each of the configured Controllers.
438 self.drivers = {
439 config.name: ControllerDriver(config, self.discovery, self.programs)
440 for config in controllers
441 }
443 async def start(self, client: SensorKit, *, task_group: Any = asyncio):
444 """Start discovery, the program state manager, all drivers, and the main operator loop."""
445 # Start discovery.
446 await self.discovery.start(client)
448 # Start the program state manager.
449 await self.programs.start(client, self.discovery, task_group=task_group)
451 # Start all drivers.
452 # FIXME: One driver's failure to start should not affect others.
453 await asyncio.gather(
454 *(driver.start(client, task_group=task_group) for driver in self.drivers.values())
455 )
457 # Start the main loop.
458 logger.info("Starting virtual operator main loop")
459 self._loop_task = task_group.create_task(self._virtual_operator())
461 async def stop(self):
462 """Cancel the main loop, stop all controller drivers, and stop program discovery."""
463 self._loop_task.cancel()
465 await asyncio.gather(
466 *(driver.stop() for driver in self.drivers.values()),
467 return_exceptions=True,
468 )
470 with contextlib.suppress(asyncio.CancelledError):
471 await self._loop_task
473 await self.discovery.stop()
475 async def _virtual_operator(self):
476 while True:
477 # Tell each driver to update its state election votes.
478 for driver in self.drivers.values():
479 driver.evaluate_state(self.election)
481 # Evaluate the election to determine the up/down demand.
482 demand = self.election.evaluate()
484 # If there is no explicit demand for a given controller, we default to down.
485 for driver in self.drivers.values():
486 demand.setdefault(driver.config.name, False)
488 for name, state in demand.items():
489 if name not in self.drivers:
490 # FIXME: This should be a config error -- can't depend on a Controller that
491 # is not being orchestrated by the Agent.
492 continue
494 # Tell the driver to make it so.
495 self.drivers[name].set_demand(state)
497 await asyncio.sleep(2)