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
« 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."""
4from __future__ import annotations
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
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
30class RegistryError(Exception):
31 """Raised for tag conflicts during ModelRegistryView resolution."""
34@dataclass(frozen=True, slots=True)
35class RegistryEntry:
36 """Metadata record for a type registered in a ModelRegistry."""
38 model_type: type
39 tag: str | None
40 namespace: str | None
43class ModelRegistryBase[T](ABC):
44 """Base for model registry types."""
46 DISCRIMINATOR_CONTEXT: ClassVar[str] = "discriminator"
47 REGISTRY_CONTEXT: ClassVar[str] = "registry"
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 ...
54 @abstractmethod
55 def __contains__(self, val: type[T]) -> bool: ...
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
63 # Only defaults declared directly on this class, not inherited attrs.
64 if field in type_.__dict__:
65 value = type_.__dict__[field]
67 if value is not None:
68 return value
70 if issubclass(type_, BaseModel):
71 field_info = type_.model_fields.get(field)
73 if field_info is not None and field_info.default is not PydanticUndefined:
74 return field_info.default
76 return None
79class ModelRegistry[T](ModelRegistryBase[T]):
80 """A mutable collection of pydantic models.
82 Types register here at import time via `__init_subclass__` hooks or decorators, with
83 optional namespace metadata.
85 Operations are not thread-safe.
86 """
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
100 for model_type in models:
101 self.add(model_type)
103 def add(self, model_type: type[T], *, tag: str | None = None, namespace: str | None = None):
104 """Register a model type in the registry.
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.
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.
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
127 if tag is None:
128 if self.discriminator_field is None:
129 raise RegistryError("cannot add model to registry without a discriminator value")
131 tag = extract_field_default_value(model_type, self.discriminator_field)
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 )
138 if model_type in self._entries:
139 raise RegistryError(f"model type {model_type.__name__} already registered")
141 self._entries[model_type] = RegistryEntry(
142 model_type=model_type, tag=tag, namespace=namespace
143 )
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}'")
149 self._tag_index[tag][namespace] = model_type
151 self._update_default_view = True
153 @property
154 def entries(self):
155 """A read-only mapping of registered model types to their `RegistryEntry` metadata."""
156 return MappingProxyType(self._entries)
158 def get_tags(self):
159 """Return all discriminator tags currently registered in this registry."""
160 return tuple(self._tag_index.keys())
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 ()
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)
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)
176 @functools.cached_property
177 def _default_view(self):
178 return self.create_resolved_view(namespace_precedence=())
180 def discriminator(self):
181 """Return a `RegistryDiscriminator` pydantic annotation backed by this registry."""
182 return RegistryDiscriminator(self)
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)
189 @override
190 def validate(self, data: Any, *, info: ValidationInfo | None = None) -> T:
191 """Validate data against registered models.
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.
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.
204 Returns:
205 A validated instance of one of the registered model types.
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
216 return self._default_view.validate(data, info=info)
218 @override
219 def __contains__(self, val: type[T]) -> bool:
220 return val in self._entries
223_registry_var: ContextVar[ModelRegistryView | None] = ContextVar("model_registry", default=None)
224"""Active ModelRegistryView for the current execution context, if any."""
227class ModelRegistryView[T](ModelRegistryBase[T]):
228 """A registry view resolving model tags by namespace precedence.
230 Call `update` to refresh the view after the registry changes.
231 """
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] = {}
239 self.update()
241 @property
242 def registry(self) -> ModelRegistry[T]:
243 """The model registry this view resolves."""
244 return self._registry
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"))
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"))
257 if prio < best_prio[1]:
258 best_prio = (ns, prio)
260 return best_prio[0]
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()
267 for tag in self._registry.get_tags():
268 namespaces = self._registry.get_namespaces(tag)
269 assert namespaces
271 # Determine the namespace that takes precedence.
272 resolved = self._resolve(tag, namespaces) if len(namespaces) > 1 else namespaces[0]
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
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
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)
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 )
299 model_type: type[T] | None = None
300 tag: str | None = None
302 if tag := tag_from_data or tag_from_context:
303 model_type = self._resolved.get(tag)
305 if model_type is None:
306 tag = self._registry.default_tag
307 model_type = self._resolved.get(tag)
309 if model_type is None:
310 raise ValueError(f"no model resolved for tag: {tag}")
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}")
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]
324 return self._registry.type_adapter(model_type).validate_python(data, context=info.context)
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
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)
340class RegistryDiscriminator:
341 """A pydantic discriminator implementation backed by a model registry or view."""
343 def __init__(self, registry: ModelRegistry):
344 self.registry = registry
346 def _validate(self, data: Any, _handler: ModelWrapValidatorHandler, info: ValidationInfo):
347 registry: ModelRegistryBase = self.registry
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
357 if isinstance(data, BaseModel):
358 model_type = type(data)
360 if model_type not in registry:
361 raise ValueError(f"model {model_type.__name__} not in registry")
363 return data
365 return registry.validate(data, info=info)
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 )
380class RegistryBaseModel(BaseModel, ABC):
381 """Base for models that register concrete subclasses by discriminator.
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.
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 """
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
405 @classmethod
406 def model_tag(cls):
407 """Get the effective discriminator value for this model class.
409 Raises:
410 KeyError: the model is not present in the registry
411 """
412 return cls.model_registry().entries[cls].tag
414 @classmethod
415 def __init_subclass__(cls, **kwargs: Any):
416 super().__init_subclass__(**kwargs)
418 # Skip abstract classes.
419 if inspect.isabstract(cls):
420 return
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
426 registry = cls.model_registry()
427 field = registry.discriminator_field
428 tag = extract_field_default_value(cls, field)
430 if tag is None:
431 tag = cls.__name__
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 )
443 registry.add(cls, tag=tag)
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)
451 if cls not in registry.entries:
452 raise RegistryError(f"Model {type(self).__name__} is not registered")
454 tag = registry.entries[cls].tag
456 if tag != registry.default_tag:
457 object.__setattr__(self, field, tag)
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
466 return None
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)