Design an Extensible Boolean Rule Evaluation Engine
Data Structure DesignModel answerLast updated
Construct an object-oriented expression tree for logical and comparison operations that evaluates safely against context dictionaries with short-circuiting.
In dynamic policy systems and filtering microservices, system rules are often constructed as structured boolean trees that evaluate metadata against key-value properties.
Design an extensible data structure representation and evaluation engine for conditional boolean rules. The system evaluates a rule tree against a flat dictionary representing target attributes (dict[str, Any]).
Requirements
-
Leaf Nodes (Comparisons):
Equals(field: str, value: Any): ReturnsTrueifcontext.get(field) == value.GreaterThan(field: str, value: Union[int, float]): ReturnsTrueifcontext.get(field) > value. If the key does not exist incontextor the values are not directly comparable, evaluate safely toFalse.InSet(field: str, values: Set[Any]): ReturnsTrueifcontext.get(field)exists withinvalues.
-
Composite Nodes (Logical Operators):
And(*predicates: Predicate): Evaluates toTrueif every child predicate yieldsTrue. Must execute short-circuit evaluation (stop assessing children as soon as aFalseresult occurs). An emptyAnd()evaluates toTrue.Or(*predicates: Predicate): Evaluates toTrueif any child predicate yieldsTrue. Must execute short-circuit evaluation (stop assessing children as soon as aTrueresult occurs). An emptyOr()evaluates toFalse.Not(predicate: Predicate): Inverts the boolean result of its child predicate.
Interface
from abc import ABC, abstractmethod
from typing import Any, Set, Union
class Predicate(ABC):
@abstractmethod
def evaluate(self, context: dict[str, Any]) -> bool:
"""Evaluates this predicate node against a target attribute map."""
pass
class Equals(Predicate):
def __init__(self, field: str, value: Any):
...
class GreaterThan(Predicate):
def __init__(self, field: str, value: Union[int, float]):
...
class InSet(Predicate):
def __init__(self, field: str, values: Set[Any]):
...
class And(Predicate):
def __init__(self, *predicates: Predicate):
...
class Or(Predicate):
def __init__(self, *predicates: Predicate):
...
class Not(Predicate):
def __init__(self, predicate: Predicate):
...
Example
rule = And(
Equals("environment", "production"),
Or(
GreaterThan("cpu_cores", 8),
InSet("tier", {"premium", "enterprise"})
)
)
server1 = {"environment": "production", "cpu_cores": 16, "tier": "standard"}
server2 = {"environment": "staging", "cpu_cores": 32, "tier": "enterprise"}
assert rule.evaluate(server1) is True # Matches environment and cpu_cores > 8
assert rule.evaluate(server2) is False # Fails environment check, short-circuits remainder
Constraints
- Target context keys map to scalar primitive values (
str,int,float,bool,None). - If an operation evaluates a field missing from
context, it must safely returnFalserather than throwing exceptions likeKeyError. - Max expression tree depth is at most 100 nodes.
Hints
Hint 1
Use the Composite structural pattern so composite logic nodes and leaf comparison nodes adhere to the identical abstract standard interface.
Hint 2
Ensure lazy evaluation in `And` and `Or` nodes by iterating over child elements through a generator rather than materializing full lists.
Hint 3
Handle type mismatches in comparison operators (e.g., comparing string values against numbers) by capturing `TypeError` and returning `False`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Approach
This problem is modeled using the Composite Pattern. Every node—whether a simple field comparison or a complex logical aggregation—implements a unified abstract interface Predicate containing the evaluate(context) method.
- Leaf Nodes (
Equals,GreaterThan,InSet) retrieve specific field values from the context dictionary and compare them against fixed targets. - Composite Nodes (
And,Or,Not) aggregate one or more childPredicateinstances and combine their boolean outputs recursively.
This design adheres to the Open/Closed Principle: new comparison operators (such as LessThan, StartsWith, or RegexMatch) can be added without modifying existing code.
And
/ \
Equals Or
(env="production") / \
GreaterThan InSet
(cpu_cores > 8) (tier in {"premium", "enterprise"})
Key Technical Details
-
Short-Circuit Evaluation: To avoid evaluating unnecessary subtrees, logical nodes should use lazy generator expressions combined with Python's short-circuiting built-ins:
And: Evaluated viaall(p.evaluate(context) for p in self.predicates). Python'sall()stops consuming the generator immediately upon encountering the firstFalse. An empty generator evaluates toTrue(logical identity for conjunction).Or: Evaluated viaany(p.evaluate(context) for p in self.predicates). Python'sany()stops consuming the generator immediately upon encountering the firstTrue. An empty generator evaluates toFalse(logical identity for disjunction).
Note: Avoid using list comprehensions like
[p.evaluate(context) for p in self.predicates]insideall()orany(), as that evaluates every node eagerly before testing the boolean conditions. -
Defensive Error Handling:
- Missing Keys: Using
context.get(field)preventsKeyError. For order comparisons likeGreaterThan, explicitly check key existence first becauseNone > targetwill raise aTypeErrorin Python 3. - Type Mismatches: Wrap comparisons in a
try...except TypeErrorblock to ensure that checking mismatched types (e.g., comparing string context fields against integer limits) returnsFalseinstead of crashing. - Immutability: Convert input collections inside
InSetconstructors tofrozensetand child predicate tuples to prevent external callers from mutating rule trees during runtime execution.
- Missing Keys: Using
Python Implementation
from abc import ABC, abstractmethod
from typing import Any, Set, Union, Tuple
class Predicate(ABC):
@abstractmethod
def evaluate(self, context: dict[str, Any]) -> bool:
"""Evaluate the predicate against the given context dictionary."""
pass
def _sanitize_children(predicates: Tuple[Any, ...]) -> Tuple[Predicate, ...]:
"""Validates that all input items conform to the Predicate interface."""
validated = []
for p in predicates:
if not isinstance(p, Predicate):
raise TypeError(f"Expected instance of Predicate, got {type(p).__name__}")
validated.append(p)
return tuple(validated)
class Equals(Predicate):
def __init__(self, field: str, value: Any):
self.field = field
self.value = value
def evaluate(self, context: dict[str, Any]) -> bool:
if self.field not in context:
return False
return bool(context[self.field] == self.value)
class GreaterThan(Predicate):
def __init__(self, field: str, value: Union[int, float]):
self.field = field
self.value = value
def evaluate(self, context: dict[str, Any]) -> bool:
if self.field not in context:
return False
val = context[self.field]
try:
return bool(val > self.value)
except TypeError:
return False
class InSet(Predicate):
def __init__(self, field: str, values: Set[Any]):
self.field = field
self.values = frozenset(values)
def evaluate(self, context: dict[str, Any]) -> bool:
if self.field not in context:
return False
try:
return context[self.field] in self.values
except TypeError: # Handle unhashable values in context safely
return False
class And(Predicate):
def __init__(self, *predicates: Predicate):
self.predicates = _sanitize_children(predicates)
def evaluate(self, context: dict[str, Any]) -> bool:
# Uses generator expression for lazy short-circuiting
return all(p.evaluate(context) for p in self.predicates)
class Or(Predicate):
def __init__(self, *predicates: Predicate):
self.predicates = _sanitize_children(predicates)
def evaluate(self, context: dict[str, Any]) -> bool:
# Uses generator expression for lazy short-circuiting
return any(p.evaluate(context) for p in self.predicates)
class Not(Predicate):
def __init__(self, predicate: Predicate):
(self.predicate,) = _sanitize_children((predicate,))
def evaluate(self, context: dict[str, Any]) -> bool:
return not self.predicate.evaluate(context)
Complexity Analysis
-
Time Complexity:
- Worst Case: $O(N)$ where $N$ is the total number of nodes in the rule expression tree.
- Average Case: Sub-linear due to short-circuiting in
AndandOrnodes. - Leaf Operations: $O(1)$ set lookup for
InSet(using hash set) and $O(1)$ equality/comparison.
-
Space Complexity:
- Recursion Stack: $O(D)$ where $D$ is the maximum tree depth. Given the constraint $D \le 100$, recursion overhead is negligible.
- Memory footprint: $O(N)$ space stored on the heap to retain the predicate tree structures.