KatInterview

Design an Extensible Boolean Rule Evaluation Engine

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designtreecomposite-pattern

Last 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

  1. Leaf Nodes (Comparisons):

    • Equals(field: str, value: Any): Returns True if context.get(field) == value.
    • GreaterThan(field: str, value: Union[int, float]): Returns True if context.get(field) > value. If the key does not exist in context or the values are not directly comparable, evaluate safely to False.
    • InSet(field: str, values: Set[Any]): Returns True if context.get(field) exists within values.
  2. Composite Nodes (Logical Operators):

    • And(*predicates: Predicate): Evaluates to True if every child predicate yields True. Must execute short-circuit evaluation (stop assessing children as soon as a False result occurs). An empty And() evaluates to True.
    • Or(*predicates: Predicate): Evaluates to True if any child predicate yields True. Must execute short-circuit evaluation (stop assessing children as soon as a True result occurs). An empty Or() evaluates to False.
    • 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 return False rather than throwing exceptions like KeyError.
  • 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`.