Coverage for core / src / sensorkit / auto / constraint.py: 97%

260 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 json 

6from abc import ABC, abstractmethod 

7from collections.abc import Sequence 

8from dataclasses import dataclass 

9from datetime import UTC, datetime, timedelta 

10from typing import Any, Literal, override 

11 

12from loguru import logger 

13from pydantic import model_validator 

14 

15from sensorkit.common.aio import cleanup_future 

16from sensorkit.common.condition import AnyCondition, resolve_field 

17from sensorkit.common.model import ModelRegistry, RegistryBaseModel 

18from sensorkit.core.client import SensorKit 

19 

20_constraint_registry = ModelRegistry(discriminator="kind") 

21_details_registry = ModelRegistry(discriminator="kind") 

22 

23 

24class Constraint(RegistryBaseModel, ABC): 

25 """Abstract operating constraint that runs a background monitoring task.""" 

26 

27 kind: str 

28 ttl: float = 30.0 

29 hold: float = 0.0 

30 optional: bool = False 

31 

32 @classmethod 

33 def model_registry(cls): 

34 return _constraint_registry 

35 

36 # FIXME: Use Context or similar instead of **kwargs 

37 @abstractmethod 

38 async def check_task(self, evaluator: ConstraintEvaluator, /, **kwargs) -> None: 

39 """Long-running coroutine that monitors the constraint and updates the evaluator.""" 

40 

41 @model_validator(mode="before") 

42 @classmethod 

43 def _compat(cls, data: Any) -> Any: 

44 if isinstance(data, dict): 

45 if "time_to_live" in data: 

46 data["ttl"] = data.pop("time_to_live") 

47 if "hold_duration" in data: 

48 data["hold"] = data.pop("hold_duration") 

49 if "activate_on_timeout" in data: 

50 data["optional"] = not data.pop("activate_on_timeout") 

51 

52 return data 

53 

54 

55class ConstraintDetails(RegistryBaseModel): 

56 """Base for structured constraint state details. Subclasses auto-register.""" 

57 

58 kind: str 

59 

60 @classmethod 

61 def model_registry(cls): 

62 return _details_registry 

63 

64 

65@dataclass 

66class ConstraintState: 

67 """Per-constraint state.""" 

68 

69 kind: str 

70 state: Literal["not_ready", "clear", "holding", "active"] = "not_ready" 

71 reason: str = "" 

72 details: ConstraintDetails | None = None 

73 

74 

75class ConstraintEvaluator: 

76 """State interface for one check_task run. Created fresh by ConstraintManager on each restart.""" 

77 

78 _QUEUE_MAXSIZE = 10 

79 

80 def __init__( 

81 self, 

82 constraint: Constraint, 

83 *, 

84 timeout: asyncio.Timeout, 

85 initial_hold: float = 0.0, 

86 ): 

87 self.constraint = constraint 

88 self.holding_until: float | None = None 

89 """Event loop deadline of the hold in effect, if there is one. 

90 

91 A hold runs on the monotonic event loop clock so that it cannot be cut short by a 

92 wall clock adjustment. Use `holding_until_dt` to express it as an instant. 

93 """ 

94 

95 self._timeout = timeout 

96 self._ready = asyncio.Event() 

97 self._hold_task: asyncio.Task | None = None 

98 

99 if self.constraint.optional: 

100 self.intended_state = ConstraintState( 

101 kind=constraint.kind, state="clear", reason="optional constraint" 

102 ) 

103 self._ready.set() 

104 else: 

105 self.intended_state = ConstraintState( 

106 kind=constraint.kind, state="not_ready", reason="awaiting data" 

107 ) 

108 

109 self.actual_state = self.intended_state 

110 self._state_updated = asyncio.Event() 

111 

112 if initial_hold > 0: 

113 self._begin_hold(initial_hold) 

114 

115 @property 

116 def is_active(self) -> bool: 

117 return self.actual_state.state != "clear" 

118 

119 @property 

120 def is_ready(self) -> bool: 

121 return self._ready.is_set() 

122 

123 async def wait_ready(self): 

124 await self._ready.wait() 

125 

126 async def next_update(self) -> ConstraintState: 

127 await self._state_updated.wait() 

128 state = self.actual_state 

129 self._state_updated.clear() 

130 return state 

131 

132 def ready(self): 

133 """Mark constraint ready.""" 

134 self._timeout.reschedule(asyncio.get_event_loop().time() + self.constraint.ttl) 

135 

136 if not self._ready.is_set(): 

137 self._ready.set() 

138 self._update_state() 

139 

140 def constrain(self, reason: str, *, details: ConstraintDetails | None = None): 

141 """Mark the constraint active and refresh its data timeout.""" 

142 self._timeout.reschedule(asyncio.get_event_loop().time() + self.constraint.ttl) 

143 self._cancel_hold() 

144 self.intended_state = ConstraintState( 

145 kind=self.constraint.kind, 

146 state="active", 

147 reason=reason, 

148 details=details, 

149 ) 

150 self._update_state() 

151 

152 def clear(self, reason: str = "", *, details: ConstraintDetails | None = None): 

153 """Refresh the data timeout and clear the constraint after any configured hold.""" 

154 self._timeout.reschedule(asyncio.get_event_loop().time() + self.constraint.ttl) 

155 

156 if self.constraint.hold > 0 and self.intended_state.state == "active": 

157 self._begin_hold(self.constraint.hold) 

158 

159 self.intended_state = ConstraintState( 

160 kind=self.constraint.kind, 

161 state="clear", 

162 reason=reason, 

163 details=details, 

164 ) 

165 self._update_state() 

166 

167 async def cleanup(self): 

168 """Stop the hold task, leaving its deadline readable by `hold_remaining`.""" 

169 self._stop_hold_task() 

170 

171 def hold_remaining(self) -> float: 

172 """Hold a replacement evaluator should start with, or zero if there is nothing to resume. 

173 

174 A hold delays releasing a constraint, so it has to outlive the evaluator that started it. 

175 Without this the replacement starts with nothing pending and releases on its first clear 

176 reading, cutting the delay short. 

177 """ 

178 if self.holding_until is not None: 

179 return max(0.0, self.holding_until - asyncio.get_event_loop().time()) 

180 

181 return self.constraint.hold if self.intended_state.state == "active" else 0.0 

182 

183 @property 

184 def holding_until_dt(self) -> datetime | None: 

185 """`holding_until` as a UTC instant, or None if no hold is in effect. 

186 

187 Projected from the current wall clock on each access rather than stored, so that a clock 

188 adjustment cannot move a hold that is already running. A deadline that has already passed 

189 projects into the past. 

190 """ 

191 if self.holding_until is None: 

192 return None 

193 

194 remaining = self.holding_until - asyncio.get_event_loop().time() 

195 

196 return datetime.now(UTC) + timedelta(seconds=remaining) 

197 

198 def _update_state(self): 

199 if not self._ready.is_set(): 

200 state = ConstraintState(kind=self.constraint.kind, state="not_ready") 

201 elif self.holding_until is not None: 

202 state = ConstraintState(kind=self.constraint.kind, state="holding") 

203 else: 

204 state = self.intended_state 

205 

206 self.actual_state = state 

207 self._state_updated.set() 

208 

209 async def _do_hold(self, wait_secs: float): 

210 logger.debug(f"holding {self.constraint.kind} constraint for {wait_secs:.1f}s") 

211 await asyncio.sleep(wait_secs) 

212 

213 # It's safe to clear the hold early here since there are no further awaits. 

214 self._hold_task = None 

215 self.holding_until = None 

216 self._update_state() 

217 

218 def _begin_hold(self, wait_secs: float): 

219 """Start a hold running for the given duration. 

220 

221 Raises: 

222 RuntimeError: if a hold is already in effect. 

223 """ 

224 if self.holding_until is not None: 

225 raise RuntimeError(f"{self.constraint.kind} constraint is already holding") 

226 

227 self.holding_until = asyncio.get_event_loop().time() + wait_secs 

228 self._hold_task = asyncio.create_task(self._do_hold(wait_secs)) 

229 self._hold_task.add_done_callback(cleanup_future) 

230 

231 def _cancel_hold(self): 

232 """Abandon any hold, discarding its deadline so it cannot be carried over.""" 

233 self._stop_hold_task() 

234 self.holding_until = None 

235 

236 def _stop_hold_task(self): 

237 if self._hold_task is not None and not self._hold_task.done(): 

238 self._hold_task.cancel() 

239 

240 self._hold_task = None 

241 

242 

243class ConstraintManager: 

244 """Manages the lifecycle of all constraints.""" 

245 

246 CONSTRAINT_RESTART_GRACE = 5.0 

247 CONSTRAINT_RESTART_DELAY = 5.0 

248 

249 def __init__(self, constraints: list[Constraint]): 

250 self._constraints = constraints 

251 self._entries: list[ConstraintState] = [ConstraintState(kind=c.kind) for c in constraints] 

252 self._constrained_set: set[int] = set() 

253 self._ready_set: set[int] = set() 

254 self._ready_event = asyncio.Event() 

255 

256 if not constraints: 

257 self._ready_event.set() 

258 

259 @property 

260 def entries(self) -> Sequence[ConstraintState]: 

261 """Current constraint state in config order.""" 

262 return self._entries 

263 

264 def is_constrained(self) -> bool: 

265 return len(self._constrained_set) > 0 

266 

267 async def start( 

268 self, 

269 *, 

270 task_group: asyncio.TaskGroup, 

271 ready_timeout: float | None = None, 

272 **kwargs, 

273 ) -> bool: 

274 """Start all constraint monitoring tasks. 

275 

276 Creates supervisor tasks for each constraint that will monitor and update 

277 their states continuously. Waits for all constraints to become ready or 

278 until the ready_timeout expires. 

279 

280 Args: 

281 task_group: The asyncio.TaskGroup to create constraint supervisor tasks in. 

282 ready_timeout: Maximum time in seconds to wait for all constraints to become ready. 

283 If None, waits indefinitely. 

284 **kwargs: Additional keyword arguments passed to each constraint's check_task method. 

285 

286 Returns: 

287 bool: True if all constraints became ready within the timeout, False if one or more 

288 constraints remain unready. 

289 """ 

290 logger.debug(f"ConstraintManager starting with {len(self._constraints)} constraints") 

291 

292 # Start a supervisor task to manage each constraint's evaluation loop. 

293 for i, constraint in enumerate(self._constraints): 

294 task_group.create_task(self._constraint_supervisor(i, constraint, **kwargs)) 

295 

296 try: 

297 async with asyncio.timeout(ready_timeout): 

298 await self._ready_event.wait() 

299 except asyncio.TimeoutError: 

300 return False 

301 

302 return True 

303 

304 def _set_state(self, idx: int, current: ConstraintState): 

305 prev = self._entries[idx] 

306 self._entries[idx] = current 

307 

308 if current.state != prev.state: 

309 state_str = current.state.replace("_", " ") 

310 reason = f"(reason: {current.reason})" if current.reason else "" 

311 logger.info(f"{current.kind.capitalize()} constraint is {state_str} {reason}") 

312 

313 if current.state == "not_ready": 

314 self._ready_set.discard(idx) 

315 self._constrained_set.add(idx) 

316 else: 

317 self._ready_set.add(idx) 

318 

319 if current.state == "clear": 

320 self._constrained_set.discard(idx) 

321 else: 

322 self._constrained_set.add(idx) 

323 

324 if len(self._ready_set) == len(self._entries): 

325 self._ready_event.set() 

326 else: 

327 self._ready_event.clear() 

328 

329 async def _constraint_supervisor(self, idx: int, constraint: Constraint, **kwargs): 

330 restarting = False 

331 initial_hold = 0.0 

332 

333 while True: 

334 evaluator: ConstraintEvaluator | None = None 

335 

336 try: 

337 initial_timeout = ( 

338 None 

339 if constraint.ttl is None 

340 else self.CONSTRAINT_RESTART_GRACE + constraint.ttl 

341 ) 

342 

343 async with asyncio.timeout(initial_timeout) as timeout: 

344 # Create a constraint evaluator and set the initial state. 

345 evaluator = ConstraintEvaluator( 

346 constraint, timeout=timeout, initial_hold=initial_hold 

347 ) 

348 self._set_state(idx, evaluator.actual_state) 

349 

350 # Sleep if this was a restart. 

351 if restarting: 

352 timeout.reschedule( 

353 None 

354 if (when := timeout.when()) is None 

355 else when + self.CONSTRAINT_RESTART_DELAY 

356 ) 

357 await asyncio.sleep(self.CONSTRAINT_RESTART_DELAY) 

358 

359 # Run the constraint and process updates. 

360 await self._constraint_task(idx, constraint, evaluator, **kwargs) 

361 except asyncio.CancelledError: 

362 # Propagate only direct cancellation. 

363 if asyncio.current_task().cancelling(): 

364 raise 

365 

366 logger.error(f"{constraint.kind.capitalize()} constraint cancelled unexpectedly") 

367 except asyncio.TimeoutError: 

368 # Only log timeouts for non-optional constraints. 

369 if not constraint.optional: 

370 logger.error(f"{constraint.kind.capitalize()} constraint timed out") 

371 except Exception: 

372 logger.exception(f"{constraint.kind.capitalize()} constraint error") 

373 

374 # A hold outlives the evaluator that started it, so the replacement resumes it. 

375 initial_hold = evaluator.hold_remaining() if evaluator is not None else 0.0 

376 restarting = True 

377 

378 async def _constraint_task( 

379 self, 

380 idx: int, 

381 constraint: Constraint, 

382 evaluator: ConstraintEvaluator, 

383 **kwargs, 

384 ): 

385 if not constraint.optional: 

386 logger.debug(f"starting {constraint.kind} constraint check") 

387 

388 # Start the constraint check task. 

389 check_task = asyncio.create_task(constraint.check_task(evaluator, **kwargs)) 

390 ready_task = asyncio.create_task(evaluator.wait_ready()) 

391 update_task: asyncio.Task | None = None 

392 

393 try: 

394 # Wait for readiness or for the check to finish. 

395 await asyncio.wait({ready_task, check_task}, return_when=asyncio.FIRST_COMPLETED) 

396 

397 if not evaluator.is_ready: 

398 # Re-raise check task exception, if any. 

399 check_task.result() 

400 return 

401 

402 # Read events emitted by the check task. 

403 while True: 

404 update_task: asyncio.Task = asyncio.create_task(evaluator.next_update()) 

405 done, _ = await asyncio.wait( 

406 {update_task, check_task}, 

407 return_when=asyncio.FIRST_COMPLETED, 

408 ) 

409 

410 if update_task in done: 

411 state = update_task.result() 

412 self._set_state(idx, state) 

413 

414 if check_task in done: 

415 # Re-raise check task exception, if any. 

416 check_task.result() 

417 break 

418 finally: 

419 aws = [evaluator.cleanup(), check_task, ready_task] 

420 check_task.cancel() 

421 ready_task.cancel() 

422 

423 if update_task: 

424 update_task.cancel() 

425 aws.append(update_task) 

426 

427 await asyncio.gather(*aws, return_exceptions=True) 

428 

429 

430class GenericConstraint(Constraint): 

431 """Generic constraint driven by a Condition evaluated against any entity keyword.""" 

432 

433 kind: Literal["conditional"] = "conditional" 

434 entity: str 

435 keyword: str 

436 field: str | None = None 

437 condition: AnyCondition 

438 

439 @override 

440 async def check_task(self, evaluator: ConstraintEvaluator, kit: SensorKit): 

441 label = f"{self.entity}.{self.keyword}" 

442 if self.field: 

443 label += f".{self.field}" 

444 logger.debug(f"monitoring conditional constraint on {label}") 

445 

446 _NONE_YET = object() 

447 previous = _NONE_YET 

448 was_active = False 

449 

450 client = kit.entity(self.entity) 

451 consumer = await client._stream.consume(self.keyword) 

452 

453 async for msg in consumer: 

454 try: 

455 data = json.loads(msg.data) 

456 except Exception: 

457 continue 

458 

459 current = resolve_field(data, self.field) if self.field else data 

460 

461 if previous is not _NONE_YET: 

462 _, is_active = self.condition.evaluate(current, previous, was_active) 

463 reason = f"{label} = {current}" 

464 

465 if is_active: 

466 evaluator.constrain(reason) 

467 else: 

468 evaluator.clear(reason) 

469 

470 evaluator.ready() 

471 was_active = is_active 

472 

473 previous = current