Coverage for core / src / sensorkit / common / model.py: 94%

223 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"""Pydantic model registry infrastructure for discriminated-union validation.""" 

3 

4from __future__ import annotations 

5 

6import collections 

7import contextlib 

8import functools 

9import inspect 

10import warnings 

11from abc import ABC, abstractmethod 

12from collections.abc import Iterable 

13from contextvars import ContextVar 

14from dataclasses import dataclass 

15from types import MappingProxyType 

16from typing import Annotated, Any, ClassVar, Self, override 

17 

18from loguru import logger 

19from pydantic import ( 

20 BaseModel, 

21 GetCoreSchemaHandler, 

22 ModelWrapValidatorHandler, 

23 TypeAdapter, 

24 ValidationInfo, 

25 WrapValidator, 

26) 

27from pydantic_core import PydanticUndefined 

28 

29 

30class RegistryError(Exception): 

31 """Raised for tag conflicts during ModelRegistryView resolution.""" 

32 

33 

34@dataclass(frozen=True, slots=True) 

35class RegistryEntry: 

36 """Metadata record for a type registered in a ModelRegistry.""" 

37 

38 model_type: type 

39 tag: str | None 

40 namespace: str | None 

41 

42 

43class ModelRegistryBase[T](ABC): 

44 """Base for model registry types.""" 

45 

46 DISCRIMINATOR_CONTEXT: ClassVar[str] = "discriminator" 

47 REGISTRY_CONTEXT: ClassVar[str] = "registry" 

48 

49 @abstractmethod 

50 def validate(self, data: Any, *, info: ValidationInfo | None = None) -> T: 

51 """Validate `data` and return a typed model instance from this registry.""" 

52 ... 

53 

54 @abstractmethod 

55 def __contains__(self, val: type[T]) -> bool: ... 

56 

57 

58def extract_field_default_value(type_: type, field: str | None): 

59 """Return the default value of `field` on `type_`, checking class dict and pydantic field info.""" 

60 if not field: 

61 return None 

62 

63 # Only defaults declared directly on this class, not inherited attrs. 

64 if field in type_.__dict__: 

65 value = type_.__dict__[field] 

66 

67 if value is not None: 

68 return value 

69 

70 if issubclass(type_, BaseModel): 

71 field_info = type_.model_fields.get(field) 

72 

73 if field_info is not None and field_info.default is not PydanticUndefined: 

74 return field_info.default 

75 

76 return None 

77 

78 

79class ModelRegistry[T](ModelRegistryBase[T]): 

80 """A mutable collection of pydantic models. 

81 

82 Types register here at import time via `__init_subclass__` hooks or decorators, with 

83 optional namespace metadata. 

84 

85 Operations are not thread-safe. 

86 """ 

87 

88 def __init__( 

89 self, 

90 *models: type[T], 

91 discriminator: str | None = None, 

92 default_tag: str | None = None, 

93 ): 

94 self.discriminator_field = discriminator 

95 self.default_tag = default_tag 

96 self._entries: dict[type[T], RegistryEntry] = {} 

97 self._tag_index: dict[str, dict[str | None, type[T]]] = collections.defaultdict(dict) 

98 self._update_default_view = False 

99 

100 for model_type in models: 

101 self.add(model_type) 

102 

103 def add(self, model_type: type[T], *, tag: str | None = None, namespace: str | None = None): 

104 """Register a model type in the registry. 

105 

106 The next time `validate()` is called, the registry cache will be updated to include the new 

107 model. This interaction is not thread safe. 

108 

109 Args: 

110 model_type: The model class to register. Abstract classes are ignored and trigger a 

111 warning. 

112 tag: Optional discriminator tag value. If None, will be extracted from the model's 

113 discriminator field default value. 

114 namespace: Optional namespace for organizing models with the same tag. 

115 

116 Raises: 

117 RegistryError: If the model type is already registered, if tag cannot be determined 

118 when no discriminator is set, if a tag conflict occurs in the same namespace, 

119 or if the registry has no discriminator field configured. 

120 """ 

121 if inspect.isabstract(model_type): 

122 warnings.warn( 

123 f"cannot add abstract type {model_type.__name__} to registry", stacklevel=2 

124 ) 

125 return 

126 

127 if tag is None: 

128 if self.discriminator_field is None: 

129 raise RegistryError("cannot add model to registry without a discriminator value") 

130 

131 tag = extract_field_default_value(model_type, self.discriminator_field) 

132 

133 if tag in (None, PydanticUndefined) and self.default_tag is None: 

134 raise RegistryError( 

135 f"could not determine discriminator value for {model_type.__name__}" 

136 ) 

137 

138 if model_type in self._entries: 

139 raise RegistryError(f"model type {model_type.__name__} already registered") 

140 

141 self._entries[model_type] = RegistryEntry( 

142 model_type=model_type, tag=tag, namespace=namespace 

143 ) 

144 

145 if tag is not None: 

146 if namespace in self._tag_index[tag]: 

147 raise RegistryError(f"tag '{tag}' already defined in namespace '{namespace}'") 

148 

149 self._tag_index[tag][namespace] = model_type 

150 

151 self._update_default_view = True 

152 

153 @property 

154 def entries(self): 

155 """A read-only mapping of registered model types to their `RegistryEntry` metadata.""" 

156 return MappingProxyType(self._entries) 

157 

158 def get_tags(self): 

159 """Return all discriminator tags currently registered in this registry.""" 

160 return tuple(self._tag_index.keys()) 

161 

162 def get_namespaces(self, tag: str): 

163 """Get all namespaces for a given tag.""" 

164 if tag in self._tag_index: 

165 return tuple(self._tag_index[tag].keys()) 

166 return () 

167 

168 def get_type(self, tag: str, namespace: str | None = None): 

169 """Return the model type registered under `tag` in the given `namespace`, or `None`.""" 

170 return self._tag_index[tag].get(namespace) 

171 

172 def create_resolved_view(self, namespace_precedence: Iterable[str]) -> ModelRegistryView: 

173 """Create a `ModelRegistryView` of this registry with key conflict resolution.""" 

174 return ModelRegistryView(self, namespace_precedence) 

175 

176 @functools.cached_property 

177 def _default_view(self): 

178 return self.create_resolved_view(namespace_precedence=()) 

179 

180 def discriminator(self): 

181 """Return a `RegistryDiscriminator` pydantic annotation backed by this registry.""" 

182 return RegistryDiscriminator(self) 

183 

184 @functools.cache 

185 def type_adapter(self, model_type: type[T]) -> TypeAdapter: 

186 """Get a cached TypeAdapter for a given model type.""" 

187 return TypeAdapter(model_type) 

188 

189 @override 

190 def validate(self, data: Any, *, info: ValidationInfo | None = None) -> T: 

191 """Validate data against registered models. 

192 

193 This method delegates validation to the default ModelRegistryView, which resolves 

194 model types based on discriminator tags without namespace precedence. The view is 

195 automatically updated if new models have been added to the registry since the last 

196 validation. 

197 

198 Args: 

199 data: The data to validate. Can be a dict, model instance, or any object with 

200 the discriminator field. 

201 info: Optional validation context information that may contain discriminator 

202 tag overrides or registry view references. 

203 

204 Returns: 

205 A validated instance of one of the registered model types. 

206 

207 Raises: 

208 ValueError: If no discriminator tag is available, if no model is found for the 

209 tag, or if there's a discriminator mismatch. 

210 RegistryError: If tag conflicts exist in the default namespace resolution. 

211 """ 

212 if self._update_default_view: 

213 self._default_view.update() 

214 self._update_default_view = False 

215 

216 return self._default_view.validate(data, info=info) 

217 

218 @override 

219 def __contains__(self, val: type[T]) -> bool: 

220 return val in self._entries 

221 

222 

223_registry_var: ContextVar[ModelRegistryView | None] = ContextVar("model_registry", default=None) 

224"""Active ModelRegistryView for the current execution context, if any.""" 

225 

226 

227class ModelRegistryView[T](ModelRegistryBase[T]): 

228 """A registry view resolving model tags by namespace precedence. 

229 

230 Call `update` to refresh the view after the registry changes. 

231 """ 

232 

233 def __init__(self, registry: ModelRegistry[T], precedence: Iterable[str] = ()): 

234 self._registry = registry 

235 self._precedence: dict[str, int] = {ns: i for i, ns in enumerate(precedence)} 

236 self._resolved: dict[str, type[T]] = {} 

237 self._index: dict[type[T], str] = {} 

238 

239 self.update() 

240 

241 @property 

242 def registry(self) -> ModelRegistry[T]: 

243 """The model registry this view resolves.""" 

244 return self._registry 

245 

246 def _resolve(self, tag: str, namespaces: tuple[str | None, ...]): 

247 logger.debug(f"resolving tag '{tag}' with namespaces: {namespaces}") 

248 best_prio = (None, float("inf")) 

249 

250 for ns in namespaces: 

251 if ns is None: 

252 if best_prio[0] is None: 

253 best_prio = (ns, float("inf")) 

254 else: 

255 prio = self._precedence.get(ns, float("inf")) 

256 

257 if prio < best_prio[1]: 

258 best_prio = (ns, prio) 

259 

260 return best_prio[0] 

261 

262 def update(self): 

263 """Update the registry view based on the current state of the underlying registry.""" 

264 self._resolved.clear() 

265 self._index.clear() 

266 

267 for tag in self._registry.get_tags(): 

268 namespaces = self._registry.get_namespaces(tag) 

269 assert namespaces 

270 

271 # Determine the namespace that takes precedence. 

272 resolved = self._resolve(tag, namespaces) if len(namespaces) > 1 else namespaces[0] 

273 

274 # Build the forward and reverse tag to model mappings. 

275 self._resolved[tag] = self._registry.get_type(tag, namespace=resolved) 

276 self._index[self._resolved[tag]] = tag 

277 

278 def validate(self, data: Any, *, info: ValidationInfo | None = None) -> T: 

279 """Validate data against this registry view.""" 

280 # Determine the tag to use for validation. 

281 tag_from_context: str | None = ( 

282 info.context.get(self.DISCRIMINATOR_CONTEXT) if info and info.context else None 

283 ) 

284 tag_from_data = None 

285 

286 if discriminator := self._registry.discriminator_field: 

287 match data: 

288 case dict(): 

289 tag_from_data = data.get(discriminator) 

290 case _: 

291 tag_from_data = getattr(data, discriminator, None) 

292 

293 # If both data and context provide a discriminator and they differ, error out. 

294 if tag_from_data and tag_from_context and tag_from_data != tag_from_context: 

295 raise ValueError( 

296 f"tag mismatch: data='{tag_from_data}' context='{tag_from_context}'" 

297 ) 

298 

299 model_type: type[T] | None = None 

300 tag: str | None = None 

301 

302 if tag := tag_from_data or tag_from_context: 

303 model_type = self._resolved.get(tag) 

304 

305 if model_type is None: 

306 tag = self._registry.default_tag 

307 model_type = self._resolved.get(tag) 

308 

309 if model_type is None: 

310 raise ValueError(f"no model resolved for tag: {tag}") 

311 

312 if not isinstance(data, dict): 

313 if type(data) is not model_type: 

314 raise ValueError(f"model {model_type.__name__} does not match tag: {tag}") 

315 

316 # Strip the discriminator context, if any. This is necessary to prevent downstream 

317 # registry-backed fields from receiving and interpreting this themselves. 

318 # FIXME: discriminator-from-context should be reviewed, as it may be avoidable by doing 

319 # namespace lookups against the registry, e.g. in `validate_keyword`. This is 

320 # slightly more complicated than it sounds to ensure views/namespaces are folded in. 

321 if tag_from_context: 

322 del info.context[self.DISCRIMINATOR_CONTEXT] 

323 

324 return self._registry.type_adapter(model_type).validate_python(data, context=info.context) 

325 

326 def __contains__(self, val: type[T]) -> bool: 

327 """Return `True` if `val` is a model type resolved by this view.""" 

328 return val in self._index 

329 

330 @contextlib.contextmanager 

331 def as_current(self): 

332 """Context manager that installs this registry as the active ContextVar.""" 

333 token = _registry_var.set(self) 

334 try: 

335 yield self 

336 finally: 

337 _registry_var.reset(token) 

338 

339 

340class RegistryDiscriminator: 

341 """A pydantic discriminator implementation backed by a model registry or view.""" 

342 

343 def __init__(self, registry: ModelRegistry): 

344 self.registry = registry 

345 

346 def _validate(self, data: Any, _handler: ModelWrapValidatorHandler, info: ValidationInfo): 

347 registry: ModelRegistryBase = self.registry 

348 

349 for view in ( 

350 info.context and info.context.get(ModelRegistryView.REGISTRY_CONTEXT), 

351 _registry_var.get(), 

352 ): 

353 if isinstance(view, ModelRegistryView) and view.registry is self.registry: 

354 registry = view 

355 break 

356 

357 if isinstance(data, BaseModel): 

358 model_type = type(data) 

359 

360 if model_type not in registry: 

361 raise ValueError(f"model {model_type.__name__} not in registry") 

362 

363 return data 

364 

365 return registry.validate(data, info=info) 

366 

367 def __get_pydantic_core_schema__( 

368 self, 

369 source_type: Any, 

370 handler: GetCoreSchemaHandler, 

371 ): 

372 return handler( 

373 Annotated[ 

374 source_type, 

375 WrapValidator(self._validate), 

376 ] 

377 ) 

378 

379 

380class RegistryBaseModel(BaseModel, ABC): 

381 """Base for models that register concrete subclasses by discriminator. 

382 

383 A direct subclass implements `model_registry` to select its registry. 

384 Concrete descendants register when defined. Their discriminator defaults to 

385 the class name unless the model supplies a value. 

386 

387 Example: 

388 >>> registry = ModelRegistry(discriminator="type") 

389 >>> class MyBase(RegistryBaseModel): 

390 ... type: str 

391 ... 

392 ... @classmethod 

393 ... def model_registry(cls): 

394 ... return registry 

395 >>> class MyModel(MyBase): 

396 ... pass 

397 """ 

398 

399 @classmethod 

400 @abstractmethod 

401 def model_registry(cls) -> ModelRegistry[Self]: 

402 """Return the `ModelRegistry` that this model class family registers into.""" 

403 raise NotImplementedError 

404 

405 @classmethod 

406 def model_tag(cls): 

407 """Get the effective discriminator value for this model class. 

408 

409 Raises: 

410 KeyError: the model is not present in the registry 

411 """ 

412 return cls.model_registry().entries[cls].tag 

413 

414 @classmethod 

415 def __init_subclass__(cls, **kwargs: Any): 

416 super().__init_subclass__(**kwargs) 

417 

418 # Skip abstract classes. 

419 if inspect.isabstract(cls): 

420 return 

421 

422 # Skip the root registered model class itself (e.g. Event), only process its subclasses. 

423 if cls is cls._find_registered_base(): 

424 return 

425 

426 registry = cls.model_registry() 

427 field = registry.discriminator_field 

428 tag = extract_field_default_value(cls, field) 

429 

430 if tag is None: 

431 tag = cls.__name__ 

432 

433 if field: 

434 # RegistryBaseModel subclasses are expected to narrow the discriminator field type 

435 # (e.g. `op: Literal["foo"] = "foo"`), which pydantic treats as field shadowing and 

436 # warns about. Suppress that warning for this specific field name. 

437 warnings.filterwarnings( 

438 "ignore", 

439 message=rf'Field name "{field}" in ".*{cls.__name__}" shadows an attribute', 

440 category=UserWarning, 

441 ) 

442 

443 registry.add(cls, tag=tag) 

444 

445 def model_post_init(self, __context: Any): 

446 """Ensure the registry's discriminator field is populated in each instance.""" 

447 registry = self.model_registry() 

448 field = registry.discriminator_field 

449 cls = type(self) 

450 

451 if cls not in registry.entries: 

452 raise RegistryError(f"Model {type(self).__name__} is not registered") 

453 

454 tag = registry.entries[cls].tag 

455 

456 if tag != registry.default_tag: 

457 object.__setattr__(self, field, tag) 

458 

459 @classmethod 

460 def _find_registered_base(cls) -> type | None: 

461 """Find the first class in the MRO that directly inherits from RegistryBaseModel.""" 

462 for klass in cls.__mro__: 

463 if RegistryBaseModel in klass.__bases__: 

464 return klass 

465 

466 return None 

467 

468 @classmethod 

469 def __get_pydantic_core_schema__(cls, source_type: Any, handler: Any): 

470 if source_type.__name__ == "RegistryBaseModel": 

471 # This class should never be validated directly, but pydantic still builds its schema. 

472 return handler(Any) 

473 elif source_type is cls._find_registered_base(): 

474 # Our direct subclasses, the "user" base model, use the registry's custom discriminator 

475 # schema to validate. 

476 return handler.generate_schema(Annotated[Any, cls.model_registry().discriminator()]) 

477 else: 

478 # Each descendant subclass, members of the registry, are validated as normal. 

479 return handler(source_type)