Coverage for core / src / sensorkit / auto / agent.py: 91%
129 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 copy
6from typing import Annotated, Any
8from loguru import logger
9from pydantic import AfterValidator, BaseModel, Field
11import sensorkit.api as sk
12from sensorkit.auto.constraint import ConstraintState
13from sensorkit.auto.lifecycle import LifecycleState
14from sensorkit.auto.operator import ControllerConfig, VirtualOperator
15from sensorkit.auto.scheduler import Schedule
16from sensorkit.core.task import TaskContextOverlay
19@sk.declare_keyword
20class ElectionVotes(BaseModel):
21 """Published election keyword: per-source, per-controller vote state for observability."""
22 votes: dict[str, dict[str, bool | None]] = Field(default_factory=dict)
25def _set_controller_config_names(configs: dict[str, ControllerConfig]):
26 for name, config in configs.items():
27 config.name = name
29 return configs
32ControllerConfigMap = Annotated[
33 dict[str, ControllerConfig],
34 AfterValidator(_set_controller_config_names),
35]
38class FirstRunConfig(BaseModel):
39 """Initial state to assume on the first run before any persisted agent state exists."""
40 operate_all: bool = False
41 enable_scheduling: bool = True
44class AgentConfig(BaseModel):
45 """Top-level agent service configuration."""
46 first_run: FirstRunConfig = Field(default_factory=FirstRunConfig)
47 controllers: ControllerConfigMap = Field(default_factory=dict)
48 contexts: TaskContextOverlay = Field(default_factory=TaskContextOverlay)
50 def model_post_init(self, __context: Any):
51 for config in self.controllers.values():
52 config.propagate_config(self.contexts)
55class AgentControllerInfo(BaseModel):
56 """Per-controller operating state: control gate, elected state, and demand override."""
57 control_enabled: bool
58 elected_state: bool | None
59 demand_override: bool | None
61 @classmethod
62 def default(cls):
63 """Return a default AgentControllerInfo with control enabled and no overrides."""
64 return cls(control_enabled=True, elected_state=None, demand_override=None)
67class AgentOperatingState(sk.Event):
68 """Event capturing the agent's global control gate and per-controller operating info."""
69 global_control_enabled: bool
70 controllers: dict[str, AgentControllerInfo] = Field(default_factory=dict)
72 def derive_for_request(self, req: AgentConfigureRequest):
73 """Return a new AgentOperatingState reflecting the changes in *req*."""
74 return AgentOperatingState(
75 global_control_enabled=(
76 req.global_control_enabled
77 if req.global_control_enabled is not None
78 else self.global_control_enabled
79 ),
80 controllers={
81 name: AgentControllerInfo(
82 control_enabled=req.controller_control_enabled.get(name, info.control_enabled),
83 elected_state=info.elected_state,
84 demand_override=req.controller_demand_override.get(name, info.demand_override),
85 )
86 for name, info in self.controllers.items()
87 },
88 )
90 def derive_for_status(self, *, votes: dict[str, bool]):
91 """Return a new AgentOperatingState updated with the latest election *votes*."""
92 return AgentOperatingState(
93 global_control_enabled=self.global_control_enabled,
94 controllers={
95 name: info.model_copy(update=dict(elected_state=votes.get(name)))
96 for name, info in self.controllers.items()
97 },
98 )
100 def derive_for_config_change(self, *, configs: ControllerConfigMap):
101 """Return an updated state reconciled against *configs*, or None if no change is needed."""
102 if set(self.controllers) == set(configs):
103 return None
105 controllers = {
106 name: info
107 for name, info in self.controllers.items()
108 if name in configs
109 }
111 for name in configs:
112 if name not in controllers:
113 controllers[name] = AgentControllerInfo.default()
115 return AgentOperatingState(
116 global_control_enabled=self.global_control_enabled,
117 controllers=controllers,
118 )
121class AgentSchedulerState(sk.Event):
122 """Event capturing the scheduler gate, program exclusions, and current schedule snapshots."""
123 scheduling_enabled: bool
124 excluded_programs: set[str] = Field(default_factory=set)
125 schedule: dict[str, Schedule] = Field(default_factory=dict)
127 def derive_for_request(self, req: AgentConfigureRequest):
128 """Return a new AgentSchedulerState reflecting the scheduler changes in *req*."""
129 return AgentSchedulerState(
130 scheduling_enabled=(
131 req.scheduling_enabled
132 if req.scheduling_enabled is not None
133 else self.scheduling_enabled
134 ),
135 excluded_programs=(
136 self.excluded_programs.union(req.add_program_exclusions).difference(
137 req.remove_program_exclusions
138 )
139 ),
140 schedule=self.schedule,
141 )
143 def derive_for_status(self, *, schedule: dict[str, Schedule]):
144 """Return a copy of this state updated with the latest *schedule* snapshots."""
145 return self.model_copy(update=dict(schedule=schedule))
148class ControllerRuntimeState(BaseModel):
149 """Observed lifecycle and constraint state of one controller."""
150 lifecycle: LifecycleState
151 constrained: bool
152 """Whether the constraints currently vote against operation."""
153 constraints: list[ConstraintState]
154 """Per-constraint state in config order."""
157class AgentRuntimeState(sk.Event):
158 """Observed per-controller runtime state, sampled at the event time.
160 Persisted observations do not initialize lifecycle counters or timing.
161 """
162 controllers: dict[str, ControllerRuntimeState] = Field(default_factory=dict)
164 @classmethod
165 def sample(cls, operator: VirtualOperator):
166 """Return a detached sample of each controller driven by *operator*."""
167 # Evaluate retry deadlines against one reference for all controllers.
168 monotonic = asyncio.get_running_loop().time()
170 return cls(
171 controllers={
172 name: ControllerRuntimeState(
173 lifecycle=driver.lifecycle.status(monotonic),
174 constrained=driver.constraints.is_constrained(),
175 constraints=copy.deepcopy(list(driver.constraints.entries)),
176 )
177 for name, driver in operator.drivers.items()
178 },
179 )
182class AgentState(sk.EventSourcedState):
183 """Persisted agent state combining operating, scheduler, and runtime sub-states."""
184 operating_state: AgentOperatingState
185 scheduler_state: AgentSchedulerState
186 runtime_state: AgentRuntimeState = Field(default_factory=AgentRuntimeState)
188 async def apply_to_operator(self, operator: VirtualOperator, configs: ControllerConfigMap):
189 """Apply program gates, demand overrides, and lifecycle gates to the operator.
191 Call this on a consistent snapshot when updates may run concurrently.
192 Use `update` with `return_snapshot=True` to obtain one.
193 """
194 if self.scheduler_state.scheduling_enabled:
195 await operator.programs.global_enable()
196 else:
197 await operator.programs.global_disable()
199 for program in operator.programs.all_programs:
200 if program in self.scheduler_state.excluded_programs:
201 await operator.programs.disable(program)
202 else:
203 await operator.programs.enable(program)
205 for controller in configs:
206 info = self.operating_state.controllers.get(controller)
208 if info:
209 operator.election.vote(
210 source="override", subject=controller, vote=info.demand_override
211 )
213 lifecycle = operator.drivers[controller].lifecycle
215 if self.operating_state.global_control_enabled:
216 if info is None or info.control_enabled:
217 lifecycle.enable()
218 continue
220 lifecycle.disable()
223class AgentConfigureRequest(BaseModel):
224 """Request payload for the agent configure RPC, specifying partial state changes."""
225 global_control_enabled: bool | None = None
226 controller_control_enabled: dict[str, bool] = Field(default_factory=dict)
227 controller_demand_override: dict[str, bool | None] = Field(default_factory=dict)
228 scheduling_enabled: bool | None = None
229 add_program_exclusions: set[str] = Field(default_factory=set)
230 remove_program_exclusions: set[str] = Field(default_factory=set)
233agent_configure_request = sk.declare_request(
234 "configure",
235 message=AgentConfigureRequest,
236 response=AgentState,
237)
240# TODO: Move this to a generic entity impl. Want a core feature to collapse single-entity services
241# into a single entity first.
242@sk.service_entrypoint(version=sk.VERSION)
243async def agent_service(service: sk.Service):
244 # Register the service.
245 await service.register()
247 # Read config.
248 config = await service.context.kv_get_model(AgentConfig)
250 # Recover state.
251 state = await AgentState.recover_or_init(
252 service.context,
253 operating_state=AgentOperatingState(global_control_enabled=config.first_run.operate_all),
254 scheduler_state=AgentSchedulerState(scheduling_enabled=config.first_run.enable_scheduling),
255 )
257 # Make sure our state structure is in agreement with configuration.
258 if update := state.operating_state.derive_for_config_change(configs=config.controllers):
259 logger.debug("controllers manifest was updated due to config change")
260 await state.update(service.context, update)
262 # Create the virtual operator and apply our initial state to it.
263 operator = VirtualOperator(config.controllers.values())
264 await state.apply_to_operator(operator, config.controllers)
266 # Replace the previous process's runtime state before startup waits on controllers.
267 await state.update(service.context, AgentRuntimeState.sample(operator))
269 # Start the virtual operator.
270 with service.context.enter_context():
271 await operator.start(client=service.client, task_group=service.context.task_group)
273 # Handle configuration requests.
274 # TODO: Bound the number of pending configuration requests. The lock serializes
275 # handlers in waiter order but does not limit how many callers can wait.
276 _configure_lock = asyncio.Lock()
278 async def _agent_configure_request(request: AgentConfigureRequest):
279 async with _configure_lock:
280 # Apply the configuration into the current state, taking a consistent snapshot to
281 # configure the operator against without racing the publish loop's updates.
282 snapshot = await state.update(
283 service.context,
284 state.scheduler_state.derive_for_request(request),
285 state.operating_state.derive_for_request(request),
286 return_snapshot=True,
287 )
289 # Configure the virtual operator to reflect the new state.
290 await snapshot.apply_to_operator(operator, config.controllers)
292 return state
294 await service.context.handle_request(agent_configure_request, _agent_configure_request)
296 async def publish():
297 while True:
298 await service.context.publish(
299 ElectionVotes(votes=operator.election._votes)
300 )
302 await state.update(
303 service.context,
304 state.scheduler_state.derive_for_status(
305 schedule={
306 name: driver.scheduler.get_schedule()
307 for name, driver in operator.drivers.items()
308 }
309 ),
310 state.operating_state.derive_for_status(votes=operator.election.evaluate()),
311 AgentRuntimeState.sample(operator),
312 )
314 await asyncio.sleep(1)
316 _publish_task = asyncio.create_task(publish())
318 # Run the service.
319 await service.run()