Coverage for core / src / sensorkit / common / predicate.py: 97%
264 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"""Pure predicates over values, and predicate-at-a-path matching against pydantic models.
4A predicate asks a static question about a value: no previous value, no edges, no deadband.
5`sensorkit.common.condition` holds the streaming form of the same idea.
7A `FieldMatch` binds a predicate to a dot path within a model. Because a path resolves against
8`model_fields` rather than against an instance, a match can be checked before any value exists:
9`FieldMatch.validate_against` rejects a path naming no field and an operand that could never
10compare against the annotation it lands on. That is the difference between a mistyped match
11failing where it is authored and one that silently never matches.
13Evaluation is deliberately more forgiving than validation, since the object read at runtime may
14not be an instance of the model the match was validated against. A path that reads nothing, or a
15value that cannot compare, resolves to `False` rather than raising.
17A value that is absent and one that is `None` are the same thing here -- nothing to compare --
18and no predicate matches either, `ne` and `not` included. `exists(False)` is the one way to
19select on absence, so a driver that publishes nothing can never satisfy a match by accident.
21A path segment applied to a collection projects over its elements, so `filters.name` on a
22`list[Filter]` reads the names as a collection. Predicates comparing against a single value
23reject such a path at validation; `contains` requires one.
24"""
26from __future__ import annotations
28import operator
29from abc import ABC, abstractmethod
30from collections.abc import Collection, Mapping
31from dataclasses import dataclass
32from enum import Enum
33from types import NoneType, UnionType
34from typing import Any, Literal, Self, Union, get_args, get_origin, override
36from pydantic import BaseModel, model_validator
39class PredicateError(ValueError):
40 """A path names no field, or an operand cannot compare against the value it addresses."""
43class Missing:
44 """Type of the `MISSING` sentinel."""
46 def __repr__(self):
47 return "MISSING"
50MISSING = Missing()
51"""Returned by `read_path` when a path reads nothing."""
54def candidates(annotation: Any) -> tuple[Any, ...]:
55 """Flatten `Annotated` wrappers and unions into the concrete annotations they admit."""
56 while hasattr(annotation, "__metadata__"):
57 annotation = annotation.__origin__
59 if get_origin(annotation) in (Union, UnionType):
60 return tuple(
61 candidate
62 for arg in get_args(annotation)
63 if arg is not NoneType
64 for candidate in candidates(arg)
65 )
67 return (annotation,)
70def collection_element(annotation: Any) -> tuple[Any, ...]:
71 """Return the element annotations of a collection annotation, or empty if it is not one."""
72 origin = get_origin(annotation)
73 base = origin or annotation
75 if not isinstance(base, type) or issubclass(base, (str, bytes, Mapping)):
76 return ()
78 if not issubclass(base, Collection):
79 return ()
81 if origin is None:
82 return (Any,)
84 return tuple(arg for arg in get_args(annotation) if arg is not Ellipsis) or (Any,)
87def is_collection(value: object) -> bool:
88 """Whether a read value should be treated as a collection of elements."""
89 return isinstance(value, Collection) and not isinstance(value, (str, bytes, Mapping))
92def accepts(annotation: Any, operand: object) -> bool:
93 """Whether `operand` could compare meaningfully against a value annotated `annotation`."""
94 base = get_origin(annotation) or annotation
96 if base is Any or not isinstance(base, type):
97 return True
99 if isinstance(operand, base):
100 return True
102 if issubclass(base, Enum):
103 return any(operand == member.value for member in base)
105 return _numeric(base) and _numeric(type(operand))
108def orderable(annotation: Any) -> bool:
109 """Whether values annotated `annotation` support `<`."""
110 base = get_origin(annotation) or annotation
112 if base is Any or not isinstance(base, type):
113 return True
115 return base.__lt__ is not object.__lt__
118def _numeric(type_: type) -> bool:
119 return issubclass(type_, (int, float)) and not issubclass(type_, bool)
122def _names(annotations: tuple[Any, ...]) -> str:
123 return " | ".join(getattr(a, "__name__", str(a)) for a in annotations)
126@dataclass(frozen=True, slots=True)
127class PathType:
128 """The static type of the value a path reads.
130 `annotations` are the candidates that value may take. `projected` marks a walk that crossed a
131 collection, which makes the value a collection of those candidates rather than one of them.
132 """
134 annotations: tuple[Any, ...]
135 projected: bool = False
137 @classmethod
138 def of(cls, annotation: Any) -> Self:
139 """Build a `PathType` for a value annotated `annotation`, with no projection."""
140 return cls(candidates(annotation))
142 def elements(self) -> tuple[Any, ...]:
143 """The annotations of the value's elements, treating it as a collection."""
144 if self.projected:
145 return self.annotations
147 return tuple(element for a in self.annotations for element in collection_element(a))
149 def collection(self) -> bool:
150 """Whether the value is a collection rather than a single comparable."""
151 return self.projected or any(collection_element(a) for a in self.annotations)
154def _step(annotation: Any, segment: str) -> tuple[tuple[Any, ...], bool]:
155 """Resolve one path segment, crossing a collection annotation to its elements."""
156 elements = collection_element(annotation)
157 resolved: list[Any] = []
159 for source in elements or (annotation,):
160 base = get_origin(source) or source
162 if isinstance(base, type) and issubclass(base, BaseModel):
163 if field := base.model_fields.get(segment):
164 resolved.extend(candidates(field.annotation))
166 return tuple(resolved), bool(elements)
169def resolve_path(model_type: type, path: str) -> PathType:
170 """Resolve a dot path against a model, returning the static type of the value it reads.
172 Args:
173 model_type: The model the path is rooted at.
174 path: Dot-separated field names. A segment applied to a collection projects over its
175 elements.
177 Raises:
178 PredicateError: A segment names no field on anything the path can reach.
179 """
180 current = PathType.of(model_type)
182 for segment in path.split("."):
183 annotations: list[Any] = []
184 projected = current.projected
186 for annotation in current.annotations:
187 resolved, crossed = _step(annotation, segment)
188 annotations.extend(resolved)
189 projected = projected or crossed
191 if not annotations:
192 raise PredicateError(
193 f"'{path}': no field '{segment}' on {_names(current.annotations)}"
194 )
196 current = PathType(tuple(annotations), projected)
198 return current
201def read_path(obj: object, path: str) -> object:
202 """Read a dot path from an object, projecting over any collection the walk crosses.
204 Returns:
205 The value read, a collection of values if the walk crossed one, or `MISSING` if the path
206 reads nothing.
207 """
208 values: tuple[Any, ...] = (obj,)
209 projected = False
211 for segment in path.split("."):
212 read: list[Any] = []
214 for value in values:
215 projected = projected or is_collection(value)
216 items = value if is_collection(value) else (value,)
218 read.extend(
219 got for item in items if (got := getattr(item, segment, MISSING)) is not MISSING
220 )
222 values = tuple(read)
224 if projected:
225 return values
227 return values[0] if values else MISSING
230def no_value(value: object) -> bool:
231 """Whether a read value carries nothing to compare against."""
232 return value is MISSING or value is None
235def _apply(fn: Any, value: object, operand: object) -> bool:
236 if no_value(value):
237 return False
239 try:
240 return bool(fn(value, operand))
241 except TypeError:
242 return False
245class Predicate(BaseModel, ABC, extra="forbid"):
246 """A static question about a value, discriminated on `op`."""
248 op: str
250 @abstractmethod
251 def test(self, value: object) -> bool:
252 """Evaluate against a value read from a path.
254 Returns `False` for a missing value or one that cannot compare, never raising.
255 """
256 ...
258 def check_operand(self, path_type: PathType):
259 """Raise if this predicate's operands could never compare against `path_type`.
261 Raises:
262 PredicateError: The operands are incompatible with the annotated value.
263 """
266class ScalarPredicate(Predicate, ABC):
267 """A predicate comparing the read value against authored operands, one value at a time."""
269 @abstractmethod
270 def operands(self) -> tuple[Any, ...]:
271 """The authored values this predicate compares against."""
272 ...
274 def ordered(self) -> bool:
275 """Whether this predicate needs a value supporting `<`."""
276 return False
278 @override
279 def check_operand(self, path_type: PathType):
280 if path_type.collection():
281 raise PredicateError(f"'{self.op}' addresses a collection; use 'contains'")
283 for operand in self.operands():
284 if not any(accepts(a, operand) for a in path_type.annotations):
285 raise PredicateError(
286 f"'{self.op}' operand {operand!r} cannot compare against "
287 f"{_names(path_type.annotations)}"
288 )
290 if self.ordered() and not all(orderable(a) for a in path_type.annotations):
291 raise PredicateError(
292 f"'{self.op}' needs an ordered value, not {_names(path_type.annotations)}"
293 )
296_COMPARISONS = {
297 "eq": operator.eq,
298 "ne": operator.ne,
299 "lt": operator.lt,
300 "le": operator.le,
301 "gt": operator.gt,
302 "ge": operator.ge,
303}
306class Compare(ScalarPredicate):
307 """Compare the read value against a single operand."""
309 op: Literal["eq", "ne", "lt", "le", "gt", "ge"]
310 value: Any
312 @override
313 def ordered(self):
314 """Only the inequalities need an ordered value."""
315 return self.op not in ("eq", "ne")
317 @override
318 def operands(self):
319 """Return the single comparison operand."""
320 return (self.value,)
322 @override
323 def test(self, value):
324 """Apply the operator, treating a missing or incomparable value as no match."""
325 return _apply(_COMPARISONS[self.op], value, self.value)
328class Between(ScalarPredicate):
329 """The read value falls within an inclusive range."""
331 op: Literal["between"] = "between"
332 low: Any
333 high: Any
335 @override
336 def ordered(self):
337 """Bounds are only meaningful against an ordered value."""
338 return True
340 @override
341 def operands(self):
342 """Return both bounds."""
343 return (self.low, self.high)
345 @override
346 def test(self, value):
347 """Match values at or between the bounds."""
348 return _apply(operator.ge, value, self.low) and _apply(operator.le, value, self.high)
351class In(ScalarPredicate):
352 """The read value is one of an authored set."""
354 op: Literal["in"] = "in"
355 values: tuple[Any, ...]
357 @override
358 def operands(self):
359 """Return the authored set."""
360 return self.values
362 @override
363 def test(self, value):
364 """Match a value equal to any member of the set."""
365 return not no_value(value) and any(value == operand for operand in self.values)
368class Contains(Predicate):
369 """The read collection contains every authored operand."""
371 op: Literal["contains"] = "contains"
372 values: tuple[Any, ...]
374 @override
375 def check_operand(self, path_type: PathType):
376 """Raise unless the path reads a collection whose elements the operands could equal."""
377 elements = path_type.elements()
379 if not elements:
380 raise PredicateError(
381 f"'contains' needs a collection, not {_names(path_type.annotations)}"
382 )
384 for operand in self.values:
385 if not any(accepts(element, operand) for element in elements):
386 raise PredicateError(
387 f"'contains' operand {operand!r} cannot equal an element of {_names(elements)}"
388 )
390 @override
391 def test(self, value):
392 """Match when every operand equals some element of the read collection."""
393 if not is_collection(value):
394 return False
396 items = tuple(value)
397 return all(any(item == operand for item in items) for operand in self.values)
400class Exists(Predicate):
401 """The path reads a value at all. An empty collection counts as absent.
403 The only predicate that sees a missing value, and so the only way to select on absence.
404 """
406 op: Literal["exists"] = "exists"
407 present: bool = True
409 @override
410 def test(self, value):
411 """Match on presence, or on absence when `present` is false."""
412 if no_value(value):
413 found = False
414 elif is_collection(value):
415 found = bool(value)
416 else:
417 found = True
419 return found is self.present
422class AllOf(Predicate):
423 """Every child predicate holds."""
425 op: Literal["all_of"] = "all_of"
426 predicates: tuple[AnyPredicate, ...]
428 @override
429 def check_operand(self, path_type: PathType):
430 """Check every child against the same path."""
431 for predicate in self.predicates:
432 predicate.check_operand(path_type)
434 @override
435 def test(self, value):
436 """Match when every child matches."""
437 return all(predicate.test(value) for predicate in self.predicates)
440class AnyOf(Predicate):
441 """At least one child predicate holds."""
443 op: Literal["any_of"] = "any_of"
444 predicates: tuple[AnyPredicate, ...]
446 @override
447 def check_operand(self, path_type: PathType):
448 """Check every child against the same path."""
449 for predicate in self.predicates:
450 predicate.check_operand(path_type)
452 @override
453 def test(self, value):
454 """Match when any child matches."""
455 return any(predicate.test(value) for predicate in self.predicates)
458class Not(Predicate):
459 """The child predicate does not hold, against a value that was read."""
461 op: Literal["not"] = "not"
462 predicate: AnyPredicate
464 @model_validator(mode="after")
465 def check_child(self) -> Self:
466 """Reject negating `exists`, which cannot hold: `not` needs a value to invert."""
467 if isinstance(self.predicate, Exists):
468 raise PredicateError("'not' cannot negate 'exists'; use exists(False)")
470 return self
472 @override
473 def check_operand(self, path_type: PathType):
474 """Check the child against the same path."""
475 self.predicate.check_operand(path_type)
477 @override
478 def test(self, value):
479 """Match when the child does not, against a value that was read."""
480 return not no_value(value) and not self.predicate.test(value)
483type AnyPredicate = Compare | Between | In | Contains | Exists | AllOf | AnyOf | Not
486class FieldMatch(BaseModel, extra="forbid"):
487 """A predicate at a dot path within some model.
489 The model is supplied by whoever owns the anchor, so this type stays agnostic about where the
490 object comes from: `validate_against` takes the type, `test` takes an instance.
491 """
493 field: str | None = None
494 predicate: AnyPredicate
496 def validate_against(self, model_type: type):
497 """Raise if this match could never hold against instances of `model_type`.
499 Raises:
500 PredicateError: The path names no field, or the predicate's operands cannot compare
501 against the value it addresses.
502 """
503 if self.field is None:
504 self.predicate.check_operand(PathType.of(model_type))
505 else:
506 self.predicate.check_operand(resolve_path(model_type, self.field))
508 def test(self, obj: object) -> bool:
509 """Evaluate the predicate against the value this match's path reads from `obj`."""
510 return self.predicate.test(obj if self.field is None else read_path(obj, self.field))
513AllOf.model_rebuild()
514AnyOf.model_rebuild()
515Not.model_rebuild()
516FieldMatch.model_rebuild()
519def eq(value: Any) -> Compare:
520 """The read value equals `value`."""
521 return Compare(op="eq", value=value)
524def ne(value: Any) -> Compare:
525 """The read value differs from `value`."""
526 return Compare(op="ne", value=value)
529def lt(value: Any) -> Compare:
530 """The read value is less than `value`."""
531 return Compare(op="lt", value=value)
534def le(value: Any) -> Compare:
535 """The read value is at most `value`."""
536 return Compare(op="le", value=value)
539def gt(value: Any) -> Compare:
540 """The read value is greater than `value`."""
541 return Compare(op="gt", value=value)
544def ge(value: Any) -> Compare:
545 """The read value is at least `value`."""
546 return Compare(op="ge", value=value)
549def between(low: Any, high: Any) -> Between:
550 """The read value lies within `low` and `high`, inclusive."""
551 return Between(low=low, high=high)
554def is_in(*values: Any) -> In:
555 """The read value is one of `values`."""
556 return In(values=values)
559def contains(*values: Any) -> Contains:
560 """The read collection contains every one of `values`."""
561 return Contains(values=values)
564def exists(present: bool = True) -> Exists:
565 """The path reads a value, or reads nothing when `present` is false."""
566 return Exists(present=present)
569def all_of(*predicates: AnyPredicate) -> AllOf:
570 """Every one of `predicates` holds."""
571 return AllOf(predicates=predicates)
574def any_of(*predicates: AnyPredicate) -> AnyOf:
575 """At least one of `predicates` holds."""
576 return AnyOf(predicates=predicates)
579def not_(predicate: AnyPredicate) -> Not:
580 """`predicate` does not hold."""
581 return Not(predicate=predicate)