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

127 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 copy 

6import uuid 

7from collections.abc import Generator 

8from datetime import datetime, timedelta 

9from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self, override 

10 

11from pydantic import BaseModel, Field, PrivateAttr, SerializeAsAny, model_validator 

12 

13from sensorkit.common.keyword import KeywordDict, declare_keyword, validated_items 

14from sensorkit.common.model import ModelRegistry, RegistryBaseModel 

15 

16if TYPE_CHECKING: 

17 from sensorkit.core.controller import InternalControllerState, TaskExecutionResult 

18 

19 

20class Task(RegistryBaseModel): 

21 """Base task definition. 

22 

23 This is the user-extensible part of the task system: subclasses add domain-specific fields and 

24 register automatically via the `task_type` discriminator. Identity and execution-envelope data 

25 (`task_id`, `controller_id`, `context`, `expiry_time`) live separately on `TaskExecution`, 

26 which the controller mints when a task is submitted for execution. 

27 """ 

28 

29 task_type: Literal[None] = None 

30 

31 # Task model registry. 

32 registry: ClassVar[ModelRegistry[Task]] = ModelRegistry(discriminator="task_type") 

33 

34 @classmethod 

35 def model_registry(cls): 

36 return cls.registry 

37 

38 def target_state(self) -> InternalControllerState | None: 

39 """Return the state-transition target if this is a lifecycle task. 

40 

41 Returns: 

42 The target controller state, or `None` for non-lifecycle tasks. 

43 """ 

44 # FIXME: This mapping should be defined by other means in controller.py. 

45 return None 

46 

47 def default_expiry(self) -> datetime | timedelta: 

48 """Return the default execution expiry for this task. 

49 

50 Used by the tasking loop when the task factory supplies no explicit `expiry_time`. A 

51 `timedelta` is interpreted relative to dispatch time; a `datetime` is absolute. Subclasses 

52 may override to express a domain-specific deadline. 

53 

54 Returns: 

55 The default expiry as an absolute time or a duration from dispatch. 

56 """ 

57 return timedelta(seconds=300) 

58 

59 def submit( 

60 self, 

61 *, 

62 context: KeywordDict | None = None, 

63 expiry_time: datetime | None = None, 

64 ) -> TaskSubmission: 

65 """Bundle this task with execution parameters into a `TaskSubmission`. 

66 

67 A convenience for task factories: `yield task.submit(expiry_time=...)` reads more fluently 

68 than constructing a `TaskSubmission` by hand. Yielding a bare task is equivalent to 

69 `task.submit()` with no parameters. 

70 

71 Args: 

72 context: Optional keyword context to attach to the execution. 

73 expiry_time: Optional time after which the execution should be considered expired. 

74 

75 Returns: 

76 A `TaskSubmission` wrapping this task and the given parameters. 

77 """ 

78 return TaskSubmission(task=self, context=context, expiry_time=expiry_time) 

79 

80 

81class InitTask(Task): 

82 """Init Task""" 

83 

84 task_type: Literal["init"] = "init" 

85 

86 @override 

87 def target_state(self): 

88 from sensorkit.core.controller import InternalControllerState 

89 

90 return InternalControllerState.OPERATE 

91 

92 

93class StandbyTask(Task): 

94 """Standby Task""" 

95 

96 task_type: Literal["standby"] = "standby" 

97 

98 @override 

99 def target_state(self): 

100 from sensorkit.core.controller import InternalControllerState 

101 

102 return InternalControllerState.STANDBY 

103 

104 

105class ShutdownTask(Task): 

106 """Shutdown Task""" 

107 

108 task_type: Literal["shutdown"] = "shutdown" 

109 

110 @override 

111 def target_state(self): 

112 from sensorkit.core.controller import InternalControllerState 

113 

114 return InternalControllerState.SHUTDOWN 

115 

116 

117class CalibrateTask(Task): 

118 """Calibrate Task""" 

119 

120 task_type: Literal["calibrate"] = "calibrate" 

121 

122 

123class RecoverTask(Task): 

124 """Recover Task""" 

125 

126 task_type: Literal["recover"] = "recover" 

127 

128 

129class CollectTask(Task): 

130 """Collect Task""" 

131 

132 task_type: Literal["collect"] = "collect" 

133 

134 

135@declare_keyword(key="Task") 

136class TaskInfo(BaseModel): 

137 """Keyword describing a task that has been executed on a controller.""" 

138 task: Task 

139 id: uuid.UUID 

140 controller_id: str 

141 

142 def get_fits_cards(self): 

143 yield "SKTASK", (self.task.task_type, "SensorKit task type") 

144 yield "SKTASKID", (str(self.id), "SensorKit task ID") 

145 yield "SKCTRL", (self.controller_id, "SensorKit controller name") 

146 

147 

148class TaskExecution[T: Task](BaseModel): 

149 """Execution envelope wrapping a `Task`. 

150 

151 Carries server-minted identity (`task_id`, `controller_id`), submitted context, 

152 working context, and expiry. The embedded `task` defines the extensible task data. 

153 

154 A handler annotated with `TaskExecution[T]` receives execution metadata and a task 

155 of type `T`. Controller-produced envelopes use the unparameterized model. 

156 Serialization preserves all fields of the concrete task subclass. 

157 Client executions returned by `ControllerClient.start_task` can be awaited for 

158 their result. 

159 """ 

160 

161 task: SerializeAsAny[T] 

162 task_id: uuid.UUID 

163 controller_id: str 

164 context: KeywordDict = Field(default_factory=KeywordDict) 

165 """Working context, including task identity and values added during execution.""" 

166 submitted_context: KeywordDict | None = None 

167 """Submitted context, captured from `context` when omitted or None. 

168 

169 Explicit mappings are retained without copying. 

170 """ 

171 expiry_time: datetime | None = None 

172 

173 # Live result future, bound only in the context that owns the in-flight call (the client 

174 # tasking loop today). Transient runtime state: excluded from serialization and equality, so a 

175 # deserialized execution carries no result future and is not awaitable. 

176 _result: asyncio.Future[TaskExecutionResult] | None = PrivateAttr(default=None) 

177 

178 @model_validator(mode="after") 

179 def _capture_submitted_context(self) -> Self: 

180 if self.submitted_context is None: 

181 self.submitted_context = copy.deepcopy(self.context) 

182 

183 return self 

184 

185 def bind_result(self, result: asyncio.Future[TaskExecutionResult]) -> None: 

186 """Bind the live result future for this execution. 

187 

188 The dispatching context binds the in-flight call's future so that holders of this execution 

189 can await its completion or inspect the result. 

190 

191 Args: 

192 result: The future resolving to this execution's final result. 

193 

194 Raises: 

195 RuntimeError: If a result future is already bound. 

196 """ 

197 if self._result is not None: 

198 raise RuntimeError("execution already has a bound result") 

199 

200 self._result = result 

201 

202 def _require_result(self) -> asyncio.Future[TaskExecutionResult]: 

203 if self._result is None: 

204 raise RuntimeError("execution is not awaitable in this context") 

205 

206 return self._result 

207 

208 def __await__(self) -> Generator[Any, None, TaskExecutionResult]: 

209 """Await the final result of this execution.""" 

210 return self._require_result().__await__() 

211 

212 def done(self) -> bool: 

213 """Return True if the execution has completed (result or error).""" 

214 return self._require_result().done() 

215 

216 def result(self) -> TaskExecutionResult: 

217 """Return the final result, raising if the execution has not yet completed.""" 

218 return self._require_result().result() 

219 

220 

221class TaskSubmission(BaseModel): 

222 """A Task bundled with client-supplied execution parameters. 

223 

224 A task factory may return this in place of a bare `Task` to attach per-instance execution 

225 parameters (`context`, `expiry_time`) that the controller records on the minted 

226 `TaskExecution`. Returning a bare `Task` is equivalent to a `TaskSubmission` with no parameters; 

227 `Task.submit` is the convenient way to build one. 

228 """ 

229 

230 task: Task 

231 context: KeywordDict | None = None 

232 expiry_time: datetime | None = None 

233 

234 

235type RawKeywords = dict[str, Any] 

236"""A sparse, unvalidated mapping of keyword key to raw payload, as declared in config.""" 

237 

238 

239def _deep_merge(base: Any, override: Any) -> Any: 

240 """Recursively merge `override` onto `base`, with `override` winning on conflict. 

241 

242 Dicts are merged key-by-key (so a keyword payload's fields combine across layers); any 

243 other value, including a list, is replaced wholesale. A `None` override keeps `base`, 

244 which lets a layer contribute a key another layer omits. 

245 """ 

246 if override is None: 

247 return base 

248 

249 if isinstance(base, dict) and isinstance(override, dict): 

250 merged = dict(base) 

251 

252 for key, value in override.items(): 

253 merged[key] = _deep_merge(base.get(key), value) 

254 

255 return merged 

256 

257 return override 

258 

259 

260class TaskContextOverlay(BaseModel, extra="allow"): 

261 """Raw, sparse, layered task context as declared in config, prior to validation. 

262 

263 The `all` field provides keywords that apply to every task type. Additional fields 

264 (`init`, `standby`, `shutdown`, or any custom task type name) provide type-specific 

265 overrides. Extra fields (via `extra="allow"`) support custom task types. 

266 

267 Values are kept as raw payloads and merged field-wise across layers; validation into 

268 keyword instances is deferred to `build`, so overlapping keywords combine rather than 

269 clobber and every payload is validated exactly once. 

270 """ 

271 

272 all: RawKeywords = Field(default_factory=dict) 

273 init: RawKeywords = Field(default_factory=dict) 

274 standby: RawKeywords = Field(default_factory=dict) 

275 shutdown: RawKeywords = Field(default_factory=dict) 

276 __pydantic_extra__: dict[str, RawKeywords] = Field(init=False) 

277 

278 def _task_type_items(self): 

279 for field, keywords in self: 

280 if field != "all": 

281 yield field, keywords 

282 

283 def propagate(self, into: TaskContextOverlay): 

284 """Merge this (parent) overlay into `into` (child), with the child taking precedence. 

285 

286 A keyword present in both layers is merged field-wise, so a child override fills in 

287 rather than replaces the parent's fields. A parent's type-specific keyword is skipped 

288 when the child already carries that keyword in its `all`, since the child's `all` 

289 already supplies it for every task type. 

290 """ 

291 for task_type, keywords in self._task_type_items(): 

292 target = getattr(into, task_type, None) 

293 

294 if target is None: 

295 target = {} 

296 setattr(into, task_type, target) 

297 

298 for key, payload in keywords.items(): 

299 if key in into.all: 

300 continue 

301 

302 target[key] = _deep_merge(payload, target.get(key)) 

303 

304 into.all = _deep_merge(self.all, into.all) 

305 

306 def build(self) -> TaskContextMap: 

307 """Flatten the `all` layer into each task type and validate every payload as a keyword.""" 

308 return TaskContextMap( 

309 defaults=KeywordDict(validated_items(self.all)), 

310 by_type={ 

311 task_type: KeywordDict(validated_items(_deep_merge(self.all, keywords))) 

312 for task_type, keywords in self._task_type_items() 

313 }, 

314 ) 

315 

316 

317class TaskContextMap(BaseModel): 

318 """Flattened, validated task contexts keyed by task type.""" 

319 

320 defaults: KeywordDict = Field(default_factory=KeywordDict) 

321 by_type: dict[str, KeywordDict] = Field(default_factory=dict) 

322 

323 def get(self, task_type: str) -> KeywordDict: 

324 """Return the effective context for `task_type`, falling back to `defaults`.""" 

325 return self.by_type.get(task_type, self.defaults).copy()