Coverage for core / src / sensorkit / sensor / policies.py: 100%

104 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Generate optional lifecycle tables and deadline rules from site policies. 

3 

4Generated models use the same compilers as authored definitions. Authored 

5tables replace generated tables by name; authored deadlines replace generated 

6rules with the same target and command. 

7 

8Compose deadline rules before connecting a session. After binding, compose 

9tables to prune generated entries that select no equipment. The compilers, 

10executor and session do not read policies directly. 

11""" 

12 

13from __future__ import annotations 

14 

15from pydantic import BaseModel 

16 

17from sensorkit.core.device import DeviceCommand 

18from sensorkit.sensor.binding import BoundSensor 

19from sensorkit.sensor.definition import SensorDefinition 

20from sensorkit.sensor.lifecycle import ( 

21 CleanupSpec, 

22 Entry, 

23 LifecycleWorkflow, 

24 OpSpec, 

25 Phase, 

26) 

27from sensorkit.sensor.selection import IsKind, Supports 

28from sensorkit.sensor.workflow import DeadlineRule 

29from sensorkit.std.enclosure import ( 

30 CloseEnclosure, 

31 OpenEnclosure, 

32 StandardEnclosure, 

33) 

34from sensorkit.std.focus import ChangeFocusPosition 

35from sensorkit.std.instrument import ConfigureCameraSensor 

36from sensorkit.std.mount import FollowTarget, StandardMount 

37from sensorkit.std.optics import ( 

38 CloseMirrorCover, 

39 OpenMirrorCover, 

40 SetFilter, 

41) 

42from sensorkit.std.traits import Connect, Deinit, Home, Init, Stop 

43 

44 

45class SensorPolicies(BaseModel, frozen=True, extra="forbid"): 

46 """Site options for generating standard lifecycle tables and deadlines. 

47 

48 A default deadline covers commands without a matching command-specific 

49 rule. 

50 """ 

51 

52 concurrent_dome_and_mount_init: bool = False 

53 """Allow dome and mount initialization to run concurrently.""" 

54 

55 concurrent_dome_and_mount_deinit: bool = False 

56 """Allow dome closure and deinitialization to overlap mount 

57 deinitialization. 

58 """ 

59 

60 concurrent_dome_init_open: bool = False 

61 """Allow dome initialization and opening to run concurrently.""" 

62 

63 concurrent_dome_deinit_close: bool = False 

64 """Allow dome closure and deinitialization to run concurrently.""" 

65 

66 always_deinit_dome: bool = False 

67 """Continue shutdown and attempt dome deinitialization after other 

68 command failures. 

69 """ 

70 

71 dome_open_close_timeout: float = 120.0 

72 """Timeout in seconds for each dome opening or closing command.""" 

73 

74 dome_init_timeout: float = 300.0 

75 """Timeout in seconds for the dome initialization command.""" 

76 

77 dome_deinit_timeout: float = 300.0 

78 """Timeout in seconds for the dome deinitialization command.""" 

79 

80 concurrent_mount_and_mirror_cover_init: bool = False 

81 """Allow mirror-cover opening to overlap mount initialization.""" 

82 

83 mirror_cover_open_close_timeout: float = 60.0 

84 """Timeout in seconds for each mirror-cover opening or closing command.""" 

85 

86 mount_init_timeout: float = 30.0 

87 """Timeout in seconds for the mount initialization command.""" 

88 

89 mount_home_timeout: float = 300.0 

90 """Timeout in seconds for the mount homing command.""" 

91 

92 mount_deinit_timeout: float = 60.0 

93 """Timeout in seconds for the mount deinitialization command.""" 

94 

95 connect_timeout: float = 60.0 

96 """Timeout in seconds for each Connect command. 

97 

98 Recovery reconnects every device before stopping any, so this and 

99 `stop_timeout` share the time limit of one recovery attempt. 

100 """ 

101 

102 stop_timeout: float = 30.0 

103 """Timeout in seconds for each Stop command.""" 

104 

105 follow_target_timeout: float = 300.0 

106 """Timeout in seconds for slewing to a target and starting to track it.""" 

107 

108 filter_change_timeout: float = 30.0 

109 """Timeout in seconds for the filter change command.""" 

110 

111 camera_configure_timeout: float = 30.0 

112 """Timeout in seconds for the camera sensor configuration command.""" 

113 

114 focus_change_timeout: float = 30.0 

115 """Timeout in seconds for the focus position command.""" 

116 

117 default_timeout: float = 300.0 

118 """Timeout in seconds for any command no other deadline rule names.""" 

119 

120 def tables(self) -> tuple[LifecycleWorkflow, ...]: 

121 """Generate `init`, `standby`, `shutdown` and `recover` tables. 

122 

123 `standby` uses the same sequence as `init`. 

124 Unsupported commands are omitted during graph compilation. `compose_tables` 

125 removes generated entries that select no equipment and applies authored 

126 table replacements. 

127 """ 

128 init = self._init_table() 

129 every = IsKind(kind="any") 

130 # Complete reconnect attempts before stopping motion. 

131 recover = LifecycleWorkflow( 

132 name="recover", 

133 fail_fast=False, 

134 phases=( 

135 Phase(name="reconnect", entries=(Entry(select=every, ops=_ops(Connect)),)), 

136 Phase(name="halt", entries=(Entry(select=every, ops=_ops(Stop)),)), 

137 ), 

138 ) 

139 

140 return (init, init.model_copy(update={"name": "standby"}), self._shutdown_table(), recover) 

141 

142 def deadlines(self) -> tuple[DeadlineRule, ...]: 

143 """Generate command deadlines for any device, and a default for every 

144 other command. 

145 

146 Commands whose limit differs by device kind are scoped to a trait, so 

147 a device failing that trait takes the default. Explicit operation 

148 timeouts and command-specific device rules can override these. 

149 """ 

150 scoped = ( 

151 (StandardEnclosure.name, Init, self.dome_init_timeout), 

152 (StandardEnclosure.name, Deinit, self.dome_deinit_timeout), 

153 (StandardMount.name, Init, self.mount_init_timeout), 

154 (StandardMount.name, Home, self.mount_home_timeout), 

155 (StandardMount.name, Deinit, self.mount_deinit_timeout), 

156 ) 

157 unscoped = ( 

158 (OpenEnclosure, self.dome_open_close_timeout), 

159 (CloseEnclosure, self.dome_open_close_timeout), 

160 (OpenMirrorCover, self.mirror_cover_open_close_timeout), 

161 (CloseMirrorCover, self.mirror_cover_open_close_timeout), 

162 (FollowTarget, self.follow_target_timeout), 

163 (SetFilter, self.filter_change_timeout), 

164 (ConfigureCameraSensor, self.camera_configure_timeout), 

165 (ChangeFocusPosition, self.focus_change_timeout), 

166 (Connect, self.connect_timeout), 

167 (Stop, self.stop_timeout), 

168 ) 

169 

170 return ( 

171 *( 

172 DeadlineRule(target=("trait", trait), command=command.model_tag(), seconds=seconds) 

173 for trait, command, seconds in scoped 

174 ), 

175 *( 

176 DeadlineRule(target=("any", None), command=command.model_tag(), seconds=seconds) 

177 for command, seconds in unscoped 

178 ), 

179 DeadlineRule(target=("any", None), seconds=self.default_timeout), 

180 ) 

181 

182 def _init_table(self) -> LifecycleWorkflow: 

183 # A dome lacking Init must still open and close. 

184 enclosure = Supports(supports=CloseEnclosure) 

185 

186 # Separate phases permit overlap without duplicate targets in a phase. 

187 if self.concurrent_dome_init_open: 

188 dome = ( 

189 Phase( 

190 name="enclosure-init", 

191 after=(), 

192 entries=(Entry(select=enclosure, ops=_ops(Init), id="init-enclosure"),), 

193 ), 

194 Phase( 

195 name="enclosure-open", 

196 after=(), 

197 entries=( 

198 Entry(select=enclosure, ops=_ops(OpenEnclosure), id="open-enclosure"), 

199 ), 

200 ), 

201 ) 

202 else: 

203 dome = ( 

204 Phase( 

205 name="enclosure", 

206 entries=( 

207 Entry( 

208 select=enclosure, 

209 ops=_ops(Init, OpenEnclosure), 

210 id="init-open-enclosure", 

211 ), 

212 ), 

213 ), 

214 ) 

215 

216 opened = tuple(phase.name for phase in dome) 

217 mount_after = () if self.concurrent_dome_and_mount_init else opened 

218 

219 # Cover opening either shares mount prerequisites or waits for dome and mount. 

220 optics_after = ( 

221 mount_after if self.concurrent_mount_and_mirror_cover_init else (*opened, "mount") 

222 ) 

223 

224 phases = ( 

225 *dome, 

226 Phase( 

227 name="mount", 

228 after=mount_after, 

229 entries=( 

230 Entry(select=Supports(supports=FollowTarget), ops=_ops(Init), id="init-mount"), 

231 ), 

232 ), 

233 Phase( 

234 name="optics", 

235 after=optics_after, 

236 entries=( 

237 Entry( 

238 select=Supports(supports=CloseMirrorCover), 

239 ops=_ops(OpenMirrorCover), 

240 id="open-mirror-cover", 

241 ), 

242 ), 

243 ), 

244 ) 

245 

246 # Any attempted bring-up command arms one halt on failure or domain abort. 

247 halt = CleanupSpec( 

248 name="halt", 

249 entries=( 

250 Entry(select=IsKind(kind="any"), ops=_ops(Stop, optional=True, fail_fast=False)), 

251 ), 

252 when="failure_or_cancelled", 

253 armed_by=tuple( 

254 entry.id for phase in phases for entry in phase.entries if entry.id is not None 

255 ), 

256 ) 

257 

258 return LifecycleWorkflow(name="init", phases=phases, fail_fast=True, cleanup=(halt,)) 

259 

260 def _shutdown_table(self) -> LifecycleWorkflow: 

261 enclosure = Supports(supports=CloseEnclosure) 

262 always = self.always_deinit_dome 

263 

264 # When always is set, failed closure must still allow deinitialization. 

265 if self.concurrent_dome_deinit_close: 

266 closing = ( 

267 Phase( 

268 name="enclosure-close", 

269 after=("halt",), 

270 entries=(Entry(select=enclosure, ops=_ops(CloseEnclosure)),), 

271 ), 

272 Phase( 

273 name="enclosure-deinit", 

274 after=("halt",), 

275 entries=(Entry(select=enclosure, ops=_ops(Deinit)),), 

276 ), 

277 ) 

278 else: 

279 closing = ( 

280 Phase( 

281 name="enclosure", 

282 after=("halt",), 

283 entries=( 

284 Entry( 

285 select=enclosure, 

286 ops=( 

287 *_ops(CloseEnclosure), 

288 *_ops(Deinit, sequence="completion" if always else "success"), 

289 ), 

290 ), 

291 ), 

292 ), 

293 ) 

294 

295 return LifecycleWorkflow( 

296 name="shutdown", 

297 fail_fast=not always, 

298 phases=( 

299 Phase( 

300 name="optics", 

301 entries=( 

302 Entry( 

303 select=Supports(supports=CloseMirrorCover), ops=_ops(CloseMirrorCover) 

304 ), 

305 ), 

306 ), 

307 Phase( 

308 name="mount", 

309 after=("optics",), 

310 entries=(Entry(select=Supports(supports=FollowTarget), ops=_ops(Deinit)),), 

311 ), 

312 # Attempt enclosure Stop before closure; failure must not block closing. 

313 Phase( 

314 name="halt", 

315 after=(("optics",) if self.concurrent_dome_and_mount_deinit else ("mount",)), 

316 entries=( 

317 Entry(select=enclosure, ops=_ops(Stop, optional=True, fail_fast=False)), 

318 ), 

319 ), 

320 *closing, 

321 ), 

322 ) 

323 

324 

325def compose_deadlines( 

326 definition: SensorDefinition, generated: tuple[DeadlineRule, ...] 

327) -> SensorDefinition: 

328 """Copy a definition with generated rules appended unless an authored 

329 rule replaces them. 

330 

331 Replacement uses the target and command pair. No device facts are required. 

332 """ 

333 authored = {(rule.target, rule.command) for rule in definition.deadlines} 

334 kept = tuple(rule for rule in generated if (rule.target, rule.command) not in authored) 

335 

336 return definition.model_copy(update={"deadlines": definition.deadlines + kept}) 

337 

338 

339def compose_tables( 

340 definition: SensorDefinition, generated: tuple[LifecycleWorkflow, ...], sensor: BoundSensor 

341) -> tuple[LifecycleWorkflow, ...]: 

342 """Return authored tables followed by unmatched generated tables pruned 

343 to the sensor. 

344 

345 Authored tables replace generated ones by name and are never pruned. In 

346 generated tables, remove empty entries but retain phases and their 

347 ordering. Prune cleanup entries and trigger ids; drop cleanup with no 

348 entries or with every formerly nonempty trigger removed. Preserve 

349 unconditional arming. 

350 

351 Raises: 

352 ValueError: The definition with composed tables fails validation. 

353 """ 

354 authored = {table.name for table in definition.tables} 

355 tables = definition.tables + tuple( 

356 _pruned(table, sensor) for table in generated if table.name not in authored 

357 ) 

358 

359 definition.model_copy(update={"tables": tables}).check() 

360 

361 return tables 

362 

363 

364def _pruned(table: LifecycleWorkflow, sensor: BoundSensor) -> LifecycleWorkflow: 

365 """Copy a generated table without empty selections, retaining its 

366 phases. 

367 """ 

368 phases = tuple( 

369 phase.model_copy( 

370 update={"entries": tuple(entry for entry in phase.entries if entry.targets(sensor))} 

371 ) 

372 for phase in table.phases 

373 ) 

374 kept = {entry.id for phase in phases for entry in phase.entries} 

375 cleanup = tuple( 

376 spec 

377 for spec in (_pruned_cleanup(spec, kept, sensor) for spec in table.cleanup) 

378 if spec is not None 

379 ) 

380 

381 return table.model_copy(update={"phases": phases, "cleanup": cleanup}) 

382 

383 

384def _pruned_cleanup( 

385 spec: CleanupSpec, kept: set[str | None], sensor: BoundSensor 

386) -> CleanupSpec | None: 

387 """Prune cleanup entries and trigger ids, or return `None` when 

388 unusable. 

389 

390 Drop specs with no remaining entries or with all formerly nonempty triggers 

391 removed. Preserve `None` and explicitly empty arming tuples. 

392 """ 

393 entries = tuple(entry for entry in spec.entries if entry.targets(sensor)) 

394 armed_by = ( 

395 None if spec.armed_by is None else tuple(name for name in spec.armed_by if name in kept) 

396 ) 

397 

398 if not entries or (spec.armed_by and not armed_by): 

399 return None 

400 

401 return spec.model_copy(update={"entries": entries, "armed_by": armed_by}) 

402 

403 

404def _ops(*commands: type[DeviceCommand], **spec) -> tuple[OpSpec, ...]: 

405 """Build default-argument commands omitted when the target lacks 

406 support. 

407 """ 

408 return tuple(OpSpec(command=command(), unsupported="omit", **spec) for command in commands)